Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 ?

like image 268
Zero Days Avatar asked Aug 14 '15 06:08

Zero Days


People also ask

What is the difference between locals () and globals () in Python?

A global variable is a variable that is accessible globally. A local variable is one that is only accessible to the current scope, such as temporary variables used in a single function definition.

What is locals () in Python?

Python locals() Function The locals() function returns the local symbol table as a dictionary. A symbol table contains necessary information about the current program.

What is the difference between global and globals in Python?

Global symbol table stores all information related to the global scope of the program, and is accessed in Python using globals() method. The functions, variables which are not associated with any class or function are stored in global scope. Syntax: globals() Parameters: No parameters required.

What do you mean by globals and locals functions?

If locals() is called from within a function, it will return all the names that can be accessed locally from that function. If globals() is called from within a function, it will return all the names that can be accessed globally from that function. The return type of both these functions is dictionary.


2 Answers

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.

like image 131
Anand S Kumar Avatar answered Sep 22 '22 09:09

Anand S Kumar


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.

  • locals returns you a dictionary of variables declared in the local scope : https://docs.python.org/2/library/functions.html#locals
  • globals returns you a dictionary of variables declared in the global scope : https://docs.python.org/2/library/functions.html#globals
  • dir works in a similar way to locals if you don't provide arguments, but if you pass an object as an argument, then it returns you a list of valid attributes for that object: https://docs.python.org/2/library/functions.html#dir
like image 38
castarco Avatar answered Sep 26 '22 09:09

castarco