Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any difference between dir() and locals() in Python?

Tags:

python

According to Python documentation, both dir() (without args) and locals() evaluates to the list of variables in something called local scope. First one returns list of names, second returns a dictionary of name-value pairs. Is it the only difference? Is this always valid?

assert dir() == sorted( locals().keys() )
like image 483
grigoryvp Avatar asked Oct 16 '12 15:10

grigoryvp


People also ask

What does locals () mean 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 locals () and globals ()?

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.

What is dir () function in Python?

Python dir() Function The dir() function returns all properties and methods of the specified object, without the values. This function will return all the properties and methods, even built-in properties which are default for all object.

What is the difference between help and dir in Python?

What is the usage of help() and dir() function in Python? dir([object]) returns all attributes of the object. help(object) generate the help of the given object.


1 Answers

The output of dir() when called without arguments is almost same as locals(), but dir() returns a list of strings and locals() returns a dictionary and you can update that dictionary to add new variables.

dir(...)
    dir([object]) -> list of strings

    If called without an argument, return the names in the current scope.


locals(...)
    locals() -> dictionary

    Update and return a dictionary containing the current scope's local variables.

Type:

>>> type(locals())
<type 'dict'>
>>> type(dir())
<type 'list'>

Update or add new variables using locals():

In [2]: locals()['a']=2

In [3]: a
Out[3]: 2

using dir(), however, this doesn't work:

In [7]: dir()[-2]
Out[7]: 'a'

In [8]: dir()[-2]=10

In [9]: dir()[-2]
Out[9]: 'a'

In [10]: a
Out[10]: 2
like image 156
Ashwini Chaudhary Avatar answered Oct 17 '22 21:10

Ashwini Chaudhary