Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Viewing all defined variables [duplicate]

I'm currently working on a computation in python shell. What I want to have is Matlab style listout where you can see all the variables that have been defined up to a point (so I know which names I've used, their values and such).

Is there a way, and how can I do that?

like image 545
Rook Avatar asked Mar 11 '09 02:03

Rook


People also ask

How do you return all variables in Python?

In Python, you can return multiple values by simply return them separated by commas.

How do you clear all variables in Jupyter notebook?

Use %reset to Clear All Variables in IPython - Requires User Confirmation. Typing in y deletes all the variables.


2 Answers

A few things you could use:

  • dir() will give you the list of in scope variables:
  • globals() will give you a dictionary of global variables
  • locals() will give you a dictionary of local variables
like image 57
RedBlueThing Avatar answered Oct 03 '22 02:10

RedBlueThing


If possible, you may want to use IPython.

To get a list of all current user-defined variables, IPython provides a magic command named who (magics must be prefixed with the % character unless the automagic feature is enabled):

In [1]: foo = 'bar' In [2]: %who foo 

You can use the whos magic to get more detail:

In [3]: %whos Variable   Type    Data/Info ---------------------------- foo        str     bar 

There are a wealth of other magics available. IPython is basically the Python interpreter on steroids. One convenient magic is store, which lets you save variables between sessions (using pickle).

Note: I am not associated with IPython Dev - just a satisfied user.

Edit:

You can find all the magic commands in the IPython Documentation.

This article also has a helpful section on the use of magic commands in Jupyter Notebook

like image 22
Chris Lawlor Avatar answered Oct 03 '22 03:10

Chris Lawlor