4 Functions That Make Reading Python Code Easier

Introduction
When a program becomes large, reading the code becomes a difficult job. Even some simple tasks will be hard. For example:
- How to quick look all variable names and values for the current script?
- How to check all variable names and values of a large function or class?
- How to get a list of valid attributes of a specific object?
Of course, we can look up the code line after line and keep the names in mind or write them in papers. However, it’s not Pythonic at all.
It’s harder to read code than to write it. — Joel Spolsky
To make our lives easier, Python provides four useful built-in functions to help us display variable names and values of a specific scope conveniently. This post will dive into these four ways to make us enjoy reading code.
Function 1: globals()
As its name implies, the globals() function will display information of global scope.
For example, if we open a Python console and input globals(), a dict including all names and values of variables in global scope will be returned.
>>> globals()
{'__name__': '__main__', '__doc__': None, ...}(Some example outputs of this post are abbreviated by ... to make them more neat and readable.)
If we add one variable:
>>> Master = "Yang"
>>> globals
{'__name__': '__main__', '__doc__': None, ... ,'Master': 'Yang'}Since the globals() function just returns a dict. We can manipulate this dict to get some specific data we are interested in:
>>> [n for n in globals() if not n.startswith('__')]
['sys', 'Master']As the above example shown, we use a list comprehension to get all the variable names without double leading underscores.
Function 2: locals()
After understanding the globals(), locals() function is just a piece of cake. As its name implies, it will return a dict including all local names and values.





