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

According to the Python documentation, both dir() (with no arguments) and locals() evaluate a list of variables in local scope . The first returns a list of names, the second returns a dictionary of name-value pairs. Is that the only difference? Is this always true?

 assert dir() == sorted( locals().keys() ) 
+6
source share
2 answers

The output of dir() when called without arguments is almost the same as locals() , but dir() returns a list of strings, and locals() returns a dictionary, and you can update this 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 local variables. 

A type:

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

Updating or adding new variables with locals() :

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

using dir() , however this does not 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 
+5
source

The exact question is: "what function to use to check if any variable is defined in the local area."

Access to the undefined variable in Python throws an exception:

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

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 the language architecture for writing better code.

This will not improve your code. You should never get into a situation where such a thing is required; this is almost always the wrong approach.

0
source

Source: https://habr.com/ru/post/927861/


All Articles