Okay, so in the past, I've made my own Python packages
with Python 2.x
(most recently, 2.7.5
). It has worked fine. Let me explain how I did that, for reference:
- Make a
directory
within the working directory. We'll call itmyPackage
. - Make a file called
__init__.py
in the directorymyPackage
. - Make sure all the modules that you want to be part of the package are imported within
__init__.py
. These modules are typically in the myPackage folder. - From a
Python
program in the working directory, type import myPackage (and it imports fine, and is usable).
However, in Python 3
, I get errors with that. (ImportError: No module named 'Whatever the first imported module is'
)
I researched the problem and found the following:
- Starred imports don't work in
Python 3.3
. - The
__init__.py
file is not required inPython 3.3
.
So, I removed the stars from my imports, and leaving the __init__.py
file in, I still got errors (ImportError: No module named 'Whatever the first imported module is'
). So, I removed the __init__.py
file, and I don't get any errors, but my package doesn't include any of my modules.
Okay, so I discovered by doing a web search for python3 __init__.py
or some such that I can do the following, although I don't have any clue if this is the standard way of doing things:
In the modules in the package, make sure there are no plain imports (not just no starred ones). Only do from myModule import stuff
. However, you need to put a .
in front of myModule
: e.g. from .myModule import stuff
. Then, I can import myPackage.oneOfMyModules
I found that by following this rule in the __init__.py
file, it also works.
Once again, I don't know if this is how it's supposed to work, but it seems to work.
I found this page that is supposed to have something to do with the changes in packages in Python 3.something, but I'm not sure how it relates to what I'm doing:
http://legacy.python.org/dev/peps/pep-0420/
So, what is the standard way to do this? Where is it documented (actually saying the syntax)? Is the way I'm doing it right? Can I do regular imports instead of from package import module
?
After analyzing some Python 3 packages installed on my system (I should have tried that to start with!) I discovered that they often seem to do things a little differently. Instead of just doing from .myModule import stuff
they would do from myPackage.myModule import stuff
(inside the modules in the package). So, that works, too, I suppose, and seems to be more frequently used.