Search code examples
pythonpython-2.7moduleattributeswebapp2

Python : Cannot find any functions within my own module?


I have created my own module with filename mymodule.py. The file contains:

def testmod():
       print "test module success"

I have placed this file within /Library/Python/2.7/site-packages/mymodule/mymodule.py

I have also added a __init__.py file, these have compiled to generate

__init__.pyc and mymodule.pyc

Then in the python console I import it

import mymodule

which works fine

when I try to use mymodule.testmod() I get the following error:

AttributeError: 'module' object has no attribute 'testmod'

So yeah it seems like it has no functions?


Solution

  • You have a package mymodule, containing a module mymodule. The function is part of the module, not the package.

    Import the module:

    import mymodule.mymodule
    

    and reference the function on that:

    mymodule.mymodule.testmod()
    

    You can use from ... import and import ... as to influence what gets imported exactly:

    from mymodule import mymodule
    
    mymodule.testmod()
    

    or

    from mymodule import mymodule as nestedmodule
    
    nestedmodule.testmod
    

    or

    from mymodule.mymodule import testmod
    
    testmod()
    

    etc.