5

If I have a src directory setup like this:

main.py
pkg1:
    __init__.py
    util.py
pkg2:
    __init__.py
    test.py

Can you tell me the best way to import pkg1.util from main.py and from test.py?

Thanks! (If I need to have another __init__.py file in the root directory, let me know?)

2 Answers 2

5

Since you mention that this is Python 3, you do not have to add the following to your .py files. I would still though because it helps backwards portability if some poor sod who's stuck on Python 2 needs to use your code:

from __future__ import absolute_import

Given that you are using Python 3, or that you're using Python 2 and have included the above line, here is your answer:

From main.py:

import pkg1.util as util

from test.py you would use one of two ways depending on whether you considered pkg1 and pkg2 to be things that would always deployed together in the same way in relation to each other, or whether they will instead always be each deployed semi-independently at the top level. If the first, you would do this:

from ..pkg1 import util

and if it's the second option, this:

import pkg1.util as util

This implies, of course, that you are always running Python from the directory in which main.py is, or that that directory is in PYTHONPATH or ends up in sys.path for some reason (like being the main Python site-packages directory for example).

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

4 Comments

If a different pkg1 exists for some reason in PYPATH, will I still get this pkg1 imported with both of these options?
@aharon: There is no option that promises you that you will get the intended pkg1 without messing with sys.path yourself to make sure the appropriate directory is first in the path. Having conflicting package names in this way is a very bad idea unless you have a package management system like setuptools that's managing the package as a 'namespace package'.
Won't all this require an __init__py in the same directory as main.py? As it is, test.py and util.py are in completely separate packages which are not subpackage of a common superpackage.
@Sven Marnach: I was assuming that main.py was a top-level package that wasn't in any sub-package when I gave my answer, but you make a good point.
1

From main.py:

import pkg1.util

From test.py:

from ..pkg1 import util

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.