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