Scopes of visibility
Namespaces are just dictionaries with some names (what we call variable name) mapped to objects (actual data in memory). This mapping allows to access target object by a name that we've assigned to it. So:
creates a reference to the "Hello World" object, and makes it accessible by variable name some_string
.
In this case our namespace will be:
In Python it's possible to have multiple namespaces (for example: each function has it's own context). When we trying to get some variable inside some namespace Python firstly looks at so-called local namespace and if it is not found it goes "upper". Such local contextual namespaces in Python called "scopes".
Scopes of visibility
All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular identifier.
Scopes of visibility in Python:
Builtin variables
Global variables
Enclosed variables
Local variables
The search is goes only in those 4 places!
Local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. Use global
to access global variable.
If a name is bound in a block, it is a local variable of that block, unless declared as nonlocal
or global
. If a name is bound at the module level, it is a global variable. (The variables of the module code block are local and global.) If a variable is used in a code block but not defined there, it is a free variable.
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
a
- free variableb
- global variablec
- local variable
In case above we don't have variable a
in local scope so we go upper - and take it from global scope.
If the nearest enclosing scope for a free variable contains a global statement, the free variable is treated as a global.
🪄 Code:
📟 Output:
Get all locals, globals:
locals()
globals()
Note: in global scope locals and globals are the same.
🪄 Code:
📟 Output:
Enclosed scope
Scope that is between global and local in nested functions
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
Introducing nonlocal
statement which marking variable as enclosed (just like global
does for global scope)
🪄 Code:
📟 Output:
Assign operation creates a local variable by default (if not global
or nonlocal
used for that variable).
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
Closures
🔥
Functions can use variables from outer scopes.
Also it's worth to mention that those variables are searched only when function is called.
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
How can inner
know about a
if foo
is already returned and all we can't access to it's local variables normally?
🪄 Code:
📟 Output:
Last updated