Viewing all defined variables in Python

Viewing all defined variables in Python

In Python, you can view all defined variables and their values using built-in functions and modules. Here's how you can do it:

1. Using the locals() Function:

The locals() function returns the dictionary of the current namespace. If called at the module level, it will provide all the globally defined variables:

a = 10 b = "hello" print(locals()) 

2. Using the globals() Function:

The globals() function returns the dictionary of the global namespace:

c = 20 d = "world" print(globals()) 

3. In IPython or Jupyter Notebook:

If you're working in an IPython shell or a Jupyter notebook, you can use the whos command:

In [1]: x = 5 In [2]: y = "Hello, world!" In [3]: whos Variable Type Data/Info ---------------------------- x int 5 y str Hello, world! 

4. Using the dir() Function:

The dir() function, without arguments, returns the list of names in the current local scope. However, this also includes built-in functions and names of imported modules, so it's a broader list than just the variables you've defined:

e = 30 f = "Python" print(dir()) 

Note:

While locals(), globals(), and dir() return dictionaries or lists that include more than just the user-defined variables (like built-in functions, imported modules, etc.), the whos command in IPython is more user-friendly and directly shows user-defined variables with their types and values.

When viewing variables using locals() or globals(), it's helpful to filter out the additional built-in attributes and functions to get a clearer view of the user-defined variables.


More Tags

buffer ipywidgets angular-material-7 unsafe pseudo-element swap signalr-hub controls server-side-rendering phasset

More Programming Guides

Other Guides

More Programming Examples