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 (e.g. 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 e.g. 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?