简体   繁体   中英

How to list all variables defined by myself in Python, excluding imported variables?

I know there are some ways to list all variable, such as locals(), globals(), dir(). But they also list the variables imported from other modules, and make a very long list, which is hard to find variables defined by myself. So how should I list all variables defined by myself, better with their values?

Here is an example:

import numpy
a=1
b=2
dir()

Then the result is:

['In',
 'Out',
 '_',
 '_1',
 '_2',
 '_3',
 '_4',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__name__',
 '__package__',
 '_dh',
 '_i',
 '_i1',
 '_i2',
 '_i3',
 '_i4',
 '_i5',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 '_sh',
 'a',
 'b',
 'exit',
 'get_ipython',
 'numpy',
 'quit']

But I only want to see variables defined in this module, ie, a and b. How should I do that?

Save the result of locals() at the top of your module, after any imports.

Any new items that subsequently show up in locals() must have been defined by you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM