I have a directory structure as follows:
root/
__main__.py
files/
__init__.py
foo.py
bar.py
baz.py
each file has an object in it with the same name as the file. You can imagine that the line foo = MyObj(1)
is in foo.py and bar = MyObj(2)
is in bar.py, etc.
In order to import the eponymous object from each file in root/files/
I have the following code in root/files/__init__.py
:
all_objects = []
#assume file_list is populated with list of files in root/files/
for file_name in file_list:
mod_name = file_name[:-3] #chop off the '.py'
obj_name = file_name[:-3] #remember, object I want has same name as module
obj = __import__(mod_name, globals=globals(), locals=locals(), fromlist=(obj_name), level=1)
all_objects.append(obj)
here, obj
holds the modules foo, bar, ...etc and not the objects contained in those modules.
The Question:
How can I change my __import__
invocation such that it will return the object contained in the module and not the module itself?
Workarounds:
I have found can do a getattr(obj, obj_name)
to extract the object I want.
__import__
. What is the problem with usinggetattr
? – BrenBarn 18 hours agofrom .mod import obj
so I should be able to do it using__import__
– turbulencetoo 18 hours agofrom blah import blah
translates to multiple statements, one to import the module and another to grab individual values from it. – BrenBarn 18 hours ago