Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
I don't think you can do that directly with __import__. What is the problem with using getattr? –  BrenBarn 18 hours ago
    
no problem, I just figured that I can do it with from .mod import obj so I should be able to do it using __import__ –  turbulencetoo 18 hours ago
1  
Not in one step. The example in the documentation (towards the end of that section) shows that from blah import blah translates to multiple statements, one to import the module and another to grab individual values from it. –  BrenBarn 18 hours ago

1 Answer 1

up vote 1 down vote accepted

You need to call something equivalent to :

obj = __import__("mymod", ...).mymod

to reproduce

from mymod import mymod

Getting the attribute of an object by its name can be done using

getattr(obj, 'mymod')
# or
obj.__dict__['mymod']
# or
vars(obj)['mymod']

Pick one. (I would go for getattr if I really had to).

obj = getattr(__import__(mod_name, globals=globals(), locals=locals(), fromlist=(obj_name), level=1), mod_name)
share|improve this answer
1  
To generalize, you can make use of operator.attrgetter to retrieve multiple values: a, b, c = attrgetter('a', 'b', 'c')(__import__("my mod", ...)). –  chepner 18 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.