rth
rth

Reputation: 3106

trouble with importing a local package

I'm gonna reorganize big chunk of my python code as a package. I suppose this package will be held in same directory where the main code is located. So the whole structure looks as follows:

project directory
\-mymod
  \-__init__.py  # totaly empty
  \-xsum.py      # with xsum function
\-main.py        # main program

Because it's just an example

#xsum.py
def xsum(a,b):
  "just xsum"
  return a+b

And inside the main.py:

#main.py
import mymod
print mymod.xsum.xsum(2,3)

Python returns an error:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print mymod.xsum.xsum(2,3)
AttributeError: 'module' object has no attribute 'xsum'

I've tried to add project directory and/or project directory/mymod to sys.path, but it doesn't help.

Upvotes: 2

Views: 87

Answers (1)

rth
rth

Reputation: 3106

Thanks @doukremt (see discussion above) I have found very simple solution: in __init__.py insert the code

import sys,os
for filename in os.listdir(os.path.dirname(__file__)):
        if filename[-3:] != ".py" or filename == "__init__.py" : continue
        exec "from "+filename[:-3]+" import *"

it allows to import all names from all py files in current package in package name space. So usage is quite simple:

import mymod
mymod.xsum(2,3)

if you would like separate modules names in a different namespaces use next code in __init__.py: import sys,os

for filename in os.listdir(os.path.dirname(__file__)):
        if filename[-3:] != ".py" or filename == "__init__.py" : continue
        exec "import "+filename[:-3]

In this case you should specify submodule:

import mymod
mymod.xsum.xsum(2,3)

Finally, if you would like import just several files in your directory, make a list and import them:

import sys,os
__all__=["a","b","c","xsum"]
for filename in __all__:
        exec "import "+filename

Upvotes: 2

Related Questions