TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to PYTHON

Python globals, locals, vars and dir

Use globals, locals, vars and dir. Call the eval, exec and compile methods.
Globals, locals. Python programs can examine their global and local variables. They can even evaluate or compile programs. These features are powerful.
Some examples. We use globals, locals, vars and dir. We further use eval, exec and compile to handle entire programs. Any Python 3 program can use these methods.Built-ins
Globals. The globals() method returns all the global variables, and their values, in a dictionary. To display them in a program, we can first copy them into another dictionary with dict.

Hidden: Some hidden variables, like __file__ are shown. These can help us understand the program's environment.

User-defined: The two user-defined global variables, named value1 and value2, are present as well. They have no surrounding underscores.

Python program that uses globals value1 = "cat" value2 = "dog" # Copy the globals dict so it does not change size. g = dict(globals()) # Loop over pairs. for item in g.items(): print(item[0], "=", item[1]) Output __builtins__ = <module 'builtins' (built-in)> __file__ = /Users/sam/Documents/test.py value2 = dog value1 = cat __cached__ = None __name__ = __main__ __doc__ = None
Locals. Locals does the same thing as globals, but for methods. Here we call locals() within a method. It displays the identifier names and values for the 3 local variables.
Python program that uses locals def method(): value1 = "bird" value2 = "fish" value3 = 400 # Display locals dictionary. print(locals()) # Call the method. method() Output {'value3': 400, 'value2': 'fish', 'value1': 'bird'}
Vars. Objects like classes have internal dictionary instances (named __dict__). We can get this dictionary from a class instance with the vars() method.

Argument: The class is the argument. Here we display the two fields (attributes) of the Bird class.

Python program that uses vars class Bird: def __init__(self, wings, color): self.wings = wings self.color = color # Create a bird. b = Bird(2, "blue") # Display internal __dict__ for Bird instance. print(vars(b)) Output {'color': 'blue', 'wings': 2}
Eval. With eval we evaluate an expression. The expression, specified as a string, is the first argument. The globals, a dictionary, is second.

And: The local variables, also a dictionary, is the third argument. This specifies the locals for the program.

Result: The eval method returns the result from evaluating the expression. Here, we find that 3 squared is equal to 9.

Python program that uses eval # Expression is first argument. # ... Global dict is second argument. # ... Local dict is third argument. result = eval("i ** 2", None, {"i": 3}) # Three squared is 9. print(result) Output 9
Compile. The compile() method returns a code object of the compiled program. We can specify a file name of a Python program to compile.

Or: We can use a string. When we compile a string, we can use an identifying string as the second argument.

Exec: We pass the string "exec" to the compile method to indicate the program has more than one line and will later be run with exec.

Caution: This method is hard to use. Please consult the Python documentation, as with help(compile) in interactive mode.

Python program that uses compile, exec # Compile this two-line program. # ... <string> means it is a string, not a file. # ... "exec" means multiple statements are present. code = compile("""x += 1 print(x)""", "<string>", "exec") # Execute compiled code with globals and locals. x = 100 exec(code, globals(), locals()) Output 101
Dir. According to the Python documentation, dir is meant to make interactive mode easier to use. So in interactive mode, you can type "dir()" to see a list of all the globals and locals.

Note: This does not get a file list in the current directly (as I first thought it might). None of us are perfect.

Python program that uses dir bird = 1 horse = 2 # Print list of names in this scope. items = list(dir()) for item in items: print(item) Output __builtins__ __cached__ __doc__ __file__ __name__ bird horse
A summary. For casual Python programs, none of these methods are helpful. Some of them, like compile(), are complex, and the detail here is not sufficient for nontrivial usage.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf