Nazar
Nazar

Reputation: 880

Import all variables from another module(s) into dictionary python

Is there a "built-in" way of importing variables from another module into dictionary in python instead of parsing the module and manually creating the dictionary? I am looking for something similar to:

from myVars import*
d = globals()

However, the approach above puts all variables (from local module and the imported module) and also includes some system vars like _ file _, _ main _ etc. which I do not want to be in the dictionary.

Given that myVars.py has the following content:

myvar1 = "Hello "
myvar2 = "world"
myvar3 = myvar1 + myvar2

I would like to have only those variables put into the dictionary when I run script.py:

from myVars import*
d = someMagicalVariableExtractionFuntion()
print(d)

would give me this:

{'myvar1': 'Hello ','myvar2': 'world','myvar3': 'Hello world'}

Upvotes: 2

Views: 1906

Answers (1)

Cireo
Cireo

Reputation: 4427

Why not use vars?

>>> import pprint
>>> import math
>>> pprint.pprint(vars(math))
{'__doc__': 'This module is always available.  It provides access to the\nmathematical functions defined by the C standard.',
 '__file__': '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/math.so',
 '__name__': 'math',
 '__package__': None,
 'acos': <built-in function acos>,
    ... <snip> ...
 'sinh': <built-in function sinh>,
 'sqrt': <built-in function sqrt>,
 'tan': <built-in function tan>,
 'tanh': <built-in function tanh>,
 'trunc': <built-in function trunc>}

If you want to filter out some special values, there are some options.

If control both sides, you can add an __all__ to the module being imported from to control import *.

If you want to get rid of magic values, you can enumerate them, or drop them by pattern:

excluded = set(['worst_value', '_bobs_my_uncle', 'xxx_secret_xxx'])
bad = lambda k: k in excluded or k.startswith('__')
d = {k: v for k, v in something.items() if not bad(k)}

Upvotes: 4

Related Questions