简体   繁体   中英

difference between locals() and globals() and dir() in python

assume this code :

>>> iterator=filter(lambda x: x % 3 == 0, [2, 18, 9, 22, 17, 24, 8, 12, 27])
>>> x=int()
>>> locals()
{'__package__': None, '__spec__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, 'iterator': <filter object at 0x02E732B0>, 'x': 0, '__doc__': None}
>>> globals()
{'__package__': None, '__spec__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, 'iterator': <filter object at 0x02E732B0>, 'x': 0, '__doc__': None}
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'iterator', 'x']
>>> 

what is the difference between locals,globals and dir ? and what is the usage ?

At global scope , both locals() and globals() return the same dictionary to global namespace . But inside a function , locals() returns the copy to the local namespace , whereas globals() would return global namespace (which would contain the global names) . So the difference between them is only visible when in a function . Example to show this -

>>> locals() == globals() #global scope, that is directly within the script (not inside a function.
True
>>> def a():
...     l = 1
...     print('locals() :',locals())
...     print('globals() :',globals())
...
>>> a()
locals() : {'l': 1}
globals() : {'BOTTOM': 'bottom', 'PROJECTING': 'proj....

From documentation of globals() -

globals()

Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

From documentation of locals() -

locals()

Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.

Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

To answer the question about usage , one usage is to be able to access variables/names using string for that. For example if you have a variable named a , and you want to access its value using the string - 'a' , you can use globals() or locals() for that as - globals()['a'] , this would return you the value of global variable a or locals()['a'] would return you the value of a in current namespace (which is global namespace when directly inside the script, or local namespace if inside a function)

dir() shows a list of attributes for the object passed in as argument , without an argument it returns the list of names in the current local namespace (similar to locals().keys() ) . From documentation of dir() -

dir([object])

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

You can notice the difference between locals and globals if you try to execute them inside a function. If you try to run them from the console without creating nested scopes the obvious result is that you wouldn't be able to notice any difference.

In global scope (such as at the interactive prompt), your locals and globals are the same. However, inside a function, they are different:

x = 'some'
y = 'this'

def foo(x):
    y = 'that'
    print "My locals: ", `locals()`
    print "My globals: ", `globals()`

# locals has x: other and y: that only
# globals contains x: some, y: this and many more global names
foo('other')

The global variable x with the value 'some' is a different variable from the local variable x with the value 'other' (and the same for the two variables named y ).

Check the builtins documentation for details, or the documentation on Python's scope rules.

And dir() without arguments is essentially the same as locals().keys() (the documentation says : Without arguments, return the list of names in the current local scope. )

globals() returns the symbols in the current global namespace (scope of current module + built-ins) in a dict -object with (key, value) -pairs. key is a string with the name of the symbol and value is the value of the symbol itself (eg the number 1 , another dict , a function, a class, etc.)

locals() returns the symbols in the current local namespace (scope of function). This will give the same result as globals() when called on module level.

dir() (without parameters) returns a list of names from the current local namespace.

When you run the following three commands on module level, they have the same values:

>>> sorted(locals().keys())
['A', '__builtins__', '__doc__', '__name__', '__package__', 'a', 'loc']
>>> sorted(dir())
['A', '__builtins__', '__doc__', '__name__', '__package__', 'a', 'loc']
>>> sorted(globals().keys())
['A', '__builtins__', '__doc__', '__name__', '__package__', 'a', 'loc']

If these three calls are made a function locals().keys() and dir() have the same values but globals() differs.

>>> def A():
...   print(sorted(locals().keys()))
...   print(sorted(dir()))
...   print(sorted(globals().keys()))

>>> A()
[]
[]
['A', 'B', '__builtins__', '__doc__', '__name__', '__package__', 'a', 'loc']

You can see the difference in use the use of globals() and locals() .

But what about dir()?

The point of dir() is, that it accepts an object as paramater. It will return a list of attribute names of that object. You can use it eg to inspect an object at runtime.

If we take the example above with the function A() , we could call:

>>> dir(A)
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']

and get all the attributes of the function object A .

There are some more details about dir() at: Difference between dir(…) and vars(…).keys() in Python?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM