0

I'm having trouble getting the two following examples to work together, dynamically loading a module and calling a function by string. I'm trying to dynamically load and call python modules.

My file structure is as follows

src/
    main.py
    __init__.py
    modules/
        __init__.py
        module1.py
        module2.py
        ...
        module100.py

In my main.py function I have the following to load the module,

mod = imp.load_source('module', '/path/to/module.py')

This seems to be working fine, print module yields

<module 'module' from '/path/to/module.py'>

In module.py I have

class module:

    def __init__(self):
        print ("HELLO WORLD")

    def calc(self):
        print ("calc called")


    if __name__ == "__main__":
        import sys
        sys.exit(not main(sys.argv))

The problem is when I try to call the calc function in module,

result = getattr(module, 'calc')()

yields the following

  HELLO WORLD
Traceback (most recent call last):
  File "main.py", line 39, in main
    result = getattr(module, 'calc')()
AttributeError: 'module' object has no attribute 'calc

I'm not sure what i'm missing or doing wrong

Community
  • 1
  • 1
pyCthon
  • 11,746
  • 20
  • 73
  • 135

1 Answers1

2

For some reason you named your class module too, which is confusing you.

Your module is, well, a module:

>>> mod = imp.load_source('module', 'module.py')
>>> mod
<module 'module' from 'module.pyc'>
>>> dir(mod)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'module']

Your class is mod.module:

>>> x = mod.module()
HELLO WORLD
>>> x
<module.module instance at 0xa1cb18c>
>>> type(x)
<type 'instance'>

Aside: the line

    self

doesn't do anything, and your calc method will need to accept an argument, or you'll get TypeError: calc() takes no arguments (1 given) when you call it.

DSM
  • 342,061
  • 65
  • 592
  • 494
  • thank you for the suggestions, but I don't see how this solves my problem. how can i call the class dynamically? won't I have to change mod.module() to something else every time? – pyCthon Feb 02 '14 at 23:47
  • or i could keep the class name the same in all the files but the functions different i suppose – pyCthon Feb 03 '14 at 04:43