Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing a python module into a dict (for use as globals in execfile())?

I'm using the Python execfile() function as a simple-but-flexible way of handling configuration files -- basically, the idea is:

# Evaluate the 'filename' file into the dictionary 'foo'.
foo = {}
execfile(filename, foo)

# Process all 'Bar' items in the dictionary.
for item in foo:
  if isinstance(item, Bar):
    # process item

This requires that my configuration file has access to the definition of the Bar class. In this simple example, that's trivial; we can just define foo = {'Bar' : Bar} rather than an empty dict. However, in the real example, I have an entire module I want to load. One obvious syntax for that is:

foo = {}
eval('from BarModule import *', foo)
execfile(filename, foo)

However, I've already imported BarModule in my top-level file, so it seems like I should be able to just directly define foo as the set of things defined by BarModule, without having to go through this chain of eval and import.

Is there a simple idiomatic way to do that?

like image 806
Brooks Moses Avatar asked Dec 27 '11 22:12

Brooks Moses


2 Answers

Maybe you can use the __dict__ defined by the module.

>>> import os
>>> str = 'getcwd()'
>>> eval(str,os.__dict__)
like image 56
anijhaw Avatar answered Oct 23 '22 19:10

anijhaw


Use the builtin vars() function to get the attributes of an object (such as a module) as a dict.

like image 43
augurar Avatar answered Oct 23 '22 17:10

augurar