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?
Maybe you can use the __dict__
defined by the module.
>>> import os
>>> str = 'getcwd()'
>>> eval(str,os.__dict__)
Use the builtin vars()
function to get the attributes of an object (such as a module) as a dict.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With