9

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() )
grigoryvp
  • 40,413
  • 64
  • 174
  • 277
  • 2
    Related post - [What's the difference between globals(), locals(), and vars()?](https://stackoverflow.com/q/7969949/465053) – RBT Aug 03 '18 at 06:34

2 Answers2

7

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
phant0m
  • 16,595
  • 5
  • 50
  • 82
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 4
    Due to the way Python optimizes access to local variables in functions, it is often not possible to change local variables using the `locals()` dictionary, which is why the documentation warns against it. – kindall Oct 16 '12 at 15:46
  • 1
    @kindall is right -- you should consider `locals()` read-only. – DSM Oct 17 '12 at 10:34
0

Exact question is 'what function to use in order to check if some variable is defined in local scope'.

Accessing an undefined variable in Python raises an exception:

>>> undefined
NameError: name 'undefined' is not defined

Just like any other exception, you can catch it:

try:
    might_exist
except NameError:
    # Variable does not exist
else:
    # Variable does exist

I need to know language architecture to write better code.

That won't make your code better. You should never get yourself into a situation where such a thing is required, it's almost always the wrong approach.

phant0m
  • 16,595
  • 5
  • 50
  • 82