Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 574
Jacob Hughes Avatar asked Apr 27 '14 09:04

Jacob Hughes


People also ask

How do I get all the functions in a Python module?

We can list down all the functions present in a Python module by simply using the dir() method in the Python shell or in the command prompt shell.

Why is Python not finding my module?

This is caused by the fact that the version of Python you're running your script with is not configured to search for modules where you've installed them. This happens when you use the wrong installation of pip to install packages.

Can functions be included within a module?

A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement. 1 (They are also run if the file is executed as a script.)


1 Answers

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.

like image 191
Martijn Pieters Avatar answered Sep 28 '22 09:09

Martijn Pieters