Mike L
Mike L

Reputation: 165

Viewing Local Variables in Spyder's Variable Explorer

I'm new to python and am using Spyder's IDE. One feature I appreciate about it is it's variable explorer. However, based on some research, I found that it only shows global variables. A workaround that I found for that is by using the inspect module:

import inspect

local_vars = {}

def main():
    global local_vars
    a = 2
    b = 4
    c = a+b
    local_vars = inspect.currentframe().f_locals
    return c

main()

This works well, however, I have other functions that are called from within main() and I'd like to see those variables in the variable explorer as well. I mimicked what was done for the variables in the main function and the dict does not appear. I noticed that when I disable the setting to "exclude unsupported data types" in Spyder's variable explorer options, the second dict appears with the right size attribute, however, I am unable to open/view it. Any ideas on a possible work around? This is my first time posting BTW.

Thanks!!


Here is a working example of my issue and I've traced it down to pylab subplots.

import inspect, pylab

mainVars = {}

def main():
    global mainVars

    a = 1
    b = 2

    fig = pylab.figure()
    subPlot = fig.add_subplot(211)    ## line of interest

    pylab.close('all')

    mainVars = inspect.currentframe().f_locals

main()

When the line of interest is commented out, the dict is created successfully and can be viewed. It appears that the object created using fig.add_subplot() is not being handled properly by the dict. It seems to be an unsupported datatype.

Hope this helps clarify the issue.

Thanks again.

Upvotes: 15

Views: 45431

Answers (2)

Carlos Cordoba
Carlos Cordoba

Reputation: 34156

To view the contents of local variables when some of them are unsupported, you have to follow these steps:

  1. Go to the options menu of the Variable Explorer (the last icon from left to right on it).

  2. Select the option called Exclude unsupported data types.

Then you'll see all local variables saved in the f_locals dict, even if you're unable to double click on it.

Upvotes: 14

chthonicdaemon
chthonicdaemon

Reputation: 19810

All of these workarounds are making your code significantly harder to read for outsiders. You have two options to inspect the values of the variables inside your function. First, you could just return the variables you are interested in:

def main():
    a = 2
    b = 4
    c = a+b

    return a, b, c

a, b, c = main()

Second, if you just want to check that the function works as expected or debug it, you can debug the function and step into it. So select Run|Debug from the menu instead of running the file directly. Then you can step into the function - the values of the variables will be visible in the variable explorer when the execution is inside the function.

Upvotes: 4

Related Questions