-
Notifications
You must be signed in to change notification settings - Fork 4.4k
[Term Entry] Python keywords: nonlocal #7981
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
af393a2
[Edit] Python: Python CLI arguments
mamtawardhani 17d337a
Update command-line-arguments.md
mamtawardhani 06bfd59
Merge branch 'Codecademy:main' into main
mamtawardhani e4aa0b1
Merge branch 'Codecademy:main' into main
mamtawardhani a25d227
Merge branch 'Codecademy:main' into main
mamtawardhani 10578df
[Term Entry] PyTorch Tensor Operations: .log2()
mamtawardhani 44eedef
Merge branch 'Codecademy:main' into main
mamtawardhani d23c8e3
Merge branch 'Codecademy:main' into main
mamtawardhani 00d603a
[Term Entry] Python keywords: nonlocal
mamtawardhani 5fbb476
Delete docs/content/pytorch/concepts/tensor-operations/terms/log2/log…
mamtawardhani d37fae8
added keywords tag
mamtawardhani 0e936b8
Apply suggestion from @avdhoottt
avdhoottt 5936f20
Apply suggestion from @avdhoottt
avdhoottt e3d532d
Apply suggestion from @avdhoottt
avdhoottt 4c19a59
Apply suggestion from @avdhoottt
avdhoottt 42111ac
Apply suggestion from @avdhoottt
avdhoottt 58d789b
Apply suggestion from @avdhoottt
avdhoottt 223fce0
Removed Keywords tag which was not used
avdhoottt dd84266
Merge branch 'main' into nonlocal
avdhoottt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
138 changes: 138 additions & 0 deletions
138
content/python/concepts/keywords/terms/nonlocal/nonlocal.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| --- | ||
| Title: 'nonlocal' | ||
| Description: 'Declares a variable inside a nested function that refers to a variable in the nearest enclosing scope (not global).' | ||
| Subjects: | ||
| - 'Computer Science' | ||
| - 'Data Science' | ||
| Tags: | ||
| - 'Attributes' | ||
| - 'Classes' | ||
| - 'Modules' | ||
| - 'Python' | ||
| CatalogContent: | ||
| - 'learn-python-3' | ||
| - 'paths/computer-science' | ||
| --- | ||
|
|
||
| The **`nonlocal`** keyword in Python is used inside nested [functions](https://www.codecademy.com/resources/docs/python/functions) to modify a [variable](https://www.codecademy.com/resources/docs/python/variables) defined in the nearest enclosing scope that is not global. It allows inner functions to change variables that belong to the outer function. Without `nonlocal`, assignments inside a nested function create a new local variable instead of updating the one in the enclosing scope. | ||
|
|
||
| This keyword is especially useful when building closures or decorators where state needs to persist across function calls without using global variables. | ||
|
|
||
| ## Syntax | ||
|
|
||
| ```pseudo | ||
| nonlocal variable_name | ||
| nonlocal variable_name1, variable_name2, ... | ||
| ``` | ||
|
|
||
| **Parameters:** | ||
|
|
||
| - `variable_name`: The name of a variable that must already be bound (previously assigned) in an enclosing (non-global) scope. Multiple variable names can be specified, separated by commas. | ||
|
|
||
| **Behavior:** | ||
|
|
||
| - Declares that the variable belongs to the nearest enclosing (non-global) function scope. The variable must already exist in that scope. | ||
| - Changes to this variable inside the inner function affect the variable in the enclosing scope. | ||
|
|
||
| ## Example 1 | ||
|
|
||
| In this example, nonlocal allows an inner function to modify a variable defined in its outer function: | ||
|
|
||
| ```py | ||
| def outer_function(): | ||
| count = 0 # variable in the enclosing scope | ||
|
|
||
| def inner_function(): | ||
| nonlocal count # refers to 'count' in outer_function | ||
| count += 1 | ||
| print("Inner count:", count) | ||
|
|
||
| inner_function() | ||
| inner_function() | ||
| print("Outer count after calls:", count) | ||
|
|
||
| outer_function() | ||
| ``` | ||
|
|
||
| The output of this code is: | ||
|
|
||
| ```shell | ||
| Inner count: 1 | ||
| Inner count: 2 | ||
| Outer count after calls: 2 | ||
| ``` | ||
|
|
||
| Here, `nonlocal` ensures that `count` is updated in the `outer_function` scope rather than creating a new local `count` each time. | ||
|
|
||
| ## Example 2 | ||
|
|
||
| In this example, `nonlocal` helps track the number of times a closure is called: | ||
|
|
||
| ```py | ||
| def make_counter(): | ||
| total = 0 | ||
|
|
||
| def counter(): | ||
| nonlocal total | ||
| total += 1 | ||
| return total | ||
|
|
||
| return counter | ||
|
|
||
| count_calls = make_counter() | ||
| print(count_calls()) | ||
| print(count_calls()) | ||
| print(count_calls()) | ||
| ``` | ||
|
|
||
| The output of this code: | ||
|
|
||
| ```shell | ||
| 1 | ||
| 2 | ||
| 3 | ||
| ``` | ||
|
|
||
| ## Codebyte Example | ||
|
|
||
| In this example, a variable in the outer function is updated from within a nested function using the `nonlocal` keyword: | ||
|
|
||
| ```py | ||
| def outer(): | ||
| name = "Alice" | ||
|
|
||
| def change_name(): | ||
| nonlocal name | ||
| name = "Bob" | ||
| print("Inside:", name) | ||
|
|
||
| change_name() | ||
| print("Outside:", name) | ||
|
|
||
| outer() | ||
| ``` | ||
|
|
||
| This ensures the change affects the variable in the enclosing scope rather than creating a new local one. | ||
|
|
||
| ## Frequently Asked Questions | ||
|
|
||
| ### 1. What is the nonlocal keyword in Python? | ||
|
|
||
| The `nonlocal` keyword lets you modify a variable in the nearest enclosing scope (not the global one) from within a nested function. | ||
|
|
||
| ### 2. What does non-local mean in Python? | ||
|
|
||
| “Non-local” refers to a variable that isn’t local to the current function but isn’t global either—it belongs to an outer function’s scope. | ||
|
|
||
| ### 3. What is a nonlocal variable? | ||
|
|
||
| A nonlocal variable is one that’s defined in an enclosing function and accessed or modified by an inner function using the nonlocal keyword. | ||
|
|
||
| ### 4. What is the difference between local and nonlocal in Python? | ||
|
|
||
| - Local variables exist only within the current function. | ||
| - Nonlocal variables refer to variables from the nearest enclosing function, allowing modification of that outer variable. | ||
|
|
||
| ### 5. Is using nonlocal in Python bad? | ||
|
|
||
| Not necessarily. `nonlocal` is safe and useful when used carefully in closures or stateful functions. However, overusing it can make code harder to read—so it’s best applied when managing shared state across nested functions. | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.