views:

46

answers:

1

I've been researching how to do this and I can't figure out what I am doing wrong, I want to use import to import a class and then instantiate it and am doing it as so:

the class, from a file called "action_1", I have already imported / appended the path to this)

class Action_1 ():
    def __init__ (self):
        pass

how I am trying to import then instantiate it

imprtd_class = __import__('action_1', globals(), locals(), ['Action_1'], -1)

#instantiate the imported class:
inst_imprtd_class = imprtd_class()
>>>> 'module' object is not callable
+1  A: 

__import__ returns the module, not anything specified in the fromlist. Check out the __import__ docs and see the example below.

>>> a1module = __import__('action_1', fromlist=['Action_1'])
>>> action1 = a1module.Action_1()
>>> print action1
<action_1.Action_1 instance at 0xb77b8a0c>

Note, the fromlist is not required in the above case, but if the action_1 module was within a package (e.g. mystuff.action_1) it is required. See the __import__ docs for more info.

sdolan
thanks for clearing this up, it works now, I hadn't realized that getattr was necessary in this case
Rick
@Rick: It's not. It's just another way of doing it. I've updated the answer... sorry for the delay, I'm a bit tired at the moment :)
sdolan