Brooks Moses
Brooks Moses

Reputation: 9537

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?

Upvotes: 7

Views: 6653

Answers (3)

augurar
augurar

Reputation: 13066

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

Upvotes: 6

merwok
merwok

Reputation: 6905

The typical solution is to use getattr:

>>> s = 'getcwd'
>>> getattr(os, s)()

Upvotes: 1

anijhaw
anijhaw

Reputation: 9422

Maybe you can use the __dict__ defined by the module.

>>> import os
>>> str = 'getcwd()'
>>> eval(str,os.__dict__)

Upvotes: 8

Related Questions