1

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 *
3
  • I don't see how having from package1 import * behave like from numpy import * would be of any good. Commented Apr 27, 2013 at 19:17
  • well I made this package for numerical simulation, so whenever I use this package, I will need numpy. That's why I want it there. Commented Apr 27, 2013 at 19:19
  • It is just that I don't like the idea of having an import obfuscating another one, but I may be wrong. Commented Apr 27, 2013 at 19:21

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.