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?)
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: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
:from
test.py
you would use one of two ways depending on whether you consideredpkg1
andpkg2
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:and if it's the second option, this:
This implies, of course, that you are always running Python from the directory in which
main.py
is, or that that directory is inPYTHONPATH
or ends up insys.path
for some reason (like being the main Python site-packages directory for example).From main.py:
From test.py: