LWZ
LWZ

Reputation: 12338

python package import modules using __init__.py

I have made a package in the following structure:

test.py
pakcage1/
    __init__.py
    module1.py
    module2.py

In the test.py file, with the code

from package1 import *

what I want it to do is to

from numpy import *
from module1 import *
from module2 import *

What should I write in __init__.py file to achieve this?

Currently in my __init__.py file I have

from numpy import *
__all__ = ['module1','module2']

and this doesn't give me what I wanted. In this way numpy wan't imported at all, and the modules are imported as

import module1

rather than

from module1 import *

Upvotes: 1

Views: 4469

Answers (2)

Truerror
Truerror

Reputation: 146

I second BrenBarn's suggestion, but be warned though, importing everything into one single namespace using from x import * is generally a bad idea, unless you know for certain that there won't be any conflicting names.

I think it's still safer to use import package.module, though it does take extra keystrokes.

Upvotes: 2

BrenBarn
BrenBarn

Reputation: 251355

If you want this, your __init__.py should contain just what you want:

from numpy import *
from module1 import *
from module2 import *

When you do from package import *, it imports all names defined in the package's __init__.py.

Note that this could become awkward if there are name clashes among the modules you import. If you just want convenient access to the functions in those modules, I would suggest using instead something like:

import numpy as np
import module1 as m1
import module2 as m2

That is, import the modules (not their contents), but under shorter names. You can then still access numpy stuff with something like np.add, which adds only three characters of typing but guards against name clashes among different modules.

Upvotes: 4

Related Questions