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

I use the Python function execfile() as a simple but flexible way to handle configuration files - basically, the idea is this:

 # 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 my configuration file to have access to the definition of the Bar class. In this simple example, this is trivial; we can simply define foo = {'Bar' : Bar} and not an empty dict. However, in a real example, I have the whole module that I want to download. One obvious syntax for this:

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

However, I have already imported BarModule into my top-level file, so it seems to me that I should just define foo as a 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 this?

+6
source share
3 answers

Perhaps you can use __dict__ defined by the module.

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

Use the built-in vars() function to get the attributes of an object (e.g. module) as a dict.

+6
source

A typical solution is to use getattr:

 >>> s = 'getcwd' >>> getattr(os, s)() 
+1
source

Source: https://habr.com/ru/post/904560/


All Articles