[Python] Python: locals and globals2011-09-09 64 people read comments (0)
Meditation> logs> Python: locals and globals
Hot1 published on 678 people have read the label: Python globals locals
Python has two built-in functions,LocalsAndGlobalsThey provide dictionary-based access to local and global variables.
First, it is a glossary about namespace. It is boring, but it is very important, so be patient. Python uses something called a namespace to record the trajectory of a variable. A namespace is just a dictionary. Its key word is the variable name, and its value is the value of those variables. In fact, the namespace can be accessed like a python dictionary. We will see it later.
There are several available namespaces in any part of a python program. Each function has its own namespace, called a local namespace. It records function variables, including function parameters and locally defined variables. Each module has its own namespace, which is called a global namespace. It records module variables, including functions, classes, other imported modules, module-level variables, and constants. There is also a built-in namespace, which can be accessed by any module. It stores built-in functions and exceptions.
When a line of code uses variablesXPython searches for variables in all available namespace in the following order:
- Local namespace-This refers to the method of the current function or class. If a function defines a local variableX, Python will use this variable, and then stop searching.
- Global namespace-specifies the current module. If the module definesXPython will use this variable and then stop searching.
- Built-in namespace-Global for each module. As the final attempt, Python assumes thatXIs a built-in function or variable.
If Python cannot be found in these namespacesX.NameerrorException.There is no variable named 'X'This information will go back to Chapter 1 and you will see this information along the way. However, you do not know how much effort Python has made before giving such an error.
|
Python 2.2 introduces a slightly different but important change that affects the search order of the namespace: Nested scopes. In Python 2.0, when you are in a nested function orLambdaWhen a variable is referenced in a function, python willLambda) In the namespace of the function, and then in the module namespace. Python 2.2 will support the current (nested orLambda) Search in the namespace of the function,Then, in the namespace of the parent FunctionAnd the module namespace. Python 2.1 can work in two ways. By default, it works in Python 2.0. However, you can add the following line of code to your module header to make your module work like python 2.2:from __future__ import nested_scopes |
Like many things in Python, namespace can be accessed directly at runtime. In particular, you can use the built-inLocalsFunction. The global (module-level) namespace can be accessed throughGlobalsFunction.
Example 4.10.LocalsIntroduction
>>> def foo(arg):
... x = 1 ... print locals() ... >>> foo(7)
{'arg': 7, 'x': 1} >>> foo('bar')
{'arg': 'bar', 'x': 1}
|
FunctionFooThere are two variables in its local namespace:ARG(Its value is passed into the function), andX(It is defined in the function ). |
|
LocalsReturns the dictionary of a name/value pair. The dictionary key is a variable name in the form of a string, and the dictionary value is the actual value of the variable. Therefore7To callFoo, The dictionary containing two local variables of the function is printed:ARG(7) AndX(1). |
|
In retrospect, Python has dynamic data types, so you can easily pass themARGA string, this function (andLocals) Will still work well.LocalsIt can be used for all types of variables. |
LocalsWhat does a local (function) namespace do,GlobalsWhat does the global (module) namespace do. HoweverGlobalsIt is even more exciting because the namespace of a module is even more exciting. [9] Not only does the module namespace contain module-level variables and constants, but also all functions and classes defined in the module. In addition, it includes anything imported into the module.
RecallFromModuleImportAndImportModule. UseImportModuleThe module itself is imported, but it maintains its own namespace. This is why you need to use the module name to access its functions or attributes (Module.Function. HoweverFromModuleImportIt is actually importing the specified functions and attributes into your own namespace from another module, which is why you can directly access them but do not need to reference the modules from which they are sourced. UseGlobalsFunction.
Example 4.11.GlobalsIntroduction
Add the following codeBasehtmlprocessor. pyMedium:
if __name__ == "__main__": for k, v in globals().items():
print k, "=", v
|
Don't be scared. Think about how you 've seen it all before.GlobalsThe function returns a dictionary. We useItemsMethods and multi-variable value assignment to traverse the dictionary. The only new thing here isGlobalsFunction. |
Run the script from the command line to get the following output:
c:\docbook\dip\py>python BaseHTMLProcessor.py
SGMLParser = sgmllib.SGMLParser
htmlentitydefs = <module 'htmlentitydefs' from 'C:\Python21\lib\htmlentitydefs.py'>
BaseHTMLProcessor = __main__.BaseHTMLProcessor
__name__ = __main__
[...]
|
SgmlparserUsedFromModuleImportSlaveSgmllib. This means that it is directly imported to our module namespace. Is imported fromSgmllib, UsingFromModuleImport. That means that it was imported directly into our module's namespace, and here it is./TD> |
|
Each module hasDoc string(Document string), you can use built-in attributes_ Doc __. This module does not clearly define document strings, so the default value isNone. |
|
This module only defines one class,BasehtmlprocessorYes. Note that the value here is the class itself, not a special class instance. |
|
RememberIf _ name __Tips? When running a module (for importing from another module), the built-in_ Name __Is a special value_ Main __. Because we run this module as a script from the command_ Name __The value is_ Main __This is why we simply print this section.GlobalsThe reason why the code can be executed. |
|
UseLocalsAndGlobalsFunction. By providing the variable string name, you can dynamically obtain the value of any variable. This method reflectsGetattr) Function (it allows you to dynamically access any function by providing the function's string name .) Mechanism. |
InLocalsAndGlobalsThere is another important difference between them. You should learn about it before it troubles you. It will bother you in any way, but at least you still remember to understand it.
Example 4.12. LocalsIs read-only,GlobalsNo
def foo(arg): x = 1 print locals()
locals()["x"] = 2
print "x=",x
z = 7 print "z=",z foo(3) globals()["z"] = 8
print "z=",z
|
Because3To callFoo, Will print out{'Arg ': 3, 'x': 1}. It should be no surprise. |
|
You may think this will change the local variableXIs2But not.LocalsActually, no local namespace is returned. It returns a copy. Therefore, modifying it does not affect the variable values in the local namespace. |
|
This will print outX = 1InsteadX = 2. |
|
WhenLocalsAfter your experience, you may thinkNoChangeZBut yes. Because Python differs internally in the implementation process (I would rather not study these differences because I have not fully understood them ),GlobalsReturns the actual global namespace instead of a copy:LocalsThe opposite is true. ThereforeGlobalsAny changes to the returned dictionary directly affect global variables. |
|
This will print outZ = 8InsteadZ = 7. |