Reputation: 22252
I wrote a simple set of python3 files for emulating a small set of mongodb features on a 32 bit platform. I fired up PyCharm and put together a directory that looked like:
minu/
client.py
database.py
collection.py
test_client.py
test_database.py
test_client.py
My imports are simple. For example, client.py
has the following at the top:
from collection import Collection
Basically, client has a Client class, collection has a Collection class, and database has a Database class. Not too tough.
As long as I cd
into the minu
directory, I can fire up a python3 interpreter and do things like:
>>> from client import Client
>>> c = Client(pathstring='something')
And everything just works. I can run the test_files as well, which use the same sorts of imports.
I'd like to modularize this, so I can use it another project by just dropping the minu directory alongside my application's .py files and just have everything work. When I do this though, and am running python3 from another directory, the local imports don't work. I placed an empty init.py in the minu directory. That made it so I could import minu
. But the others broke. I tried using things like from .collection import Collection
(added the dot), but then I can't run things in the original directory anymore, like I could before. What is the simple/right way to do this?
I have looked around a bit with Dr. Google, but none of the examples really clarify it well, feel free to point out the one I missed
Upvotes: 0
Views: 89
Reputation: 28243
In this file ...minu/__init__.py
import the submodules you wish to expose externally.
If the __init__.py
file contains the following lines, and the client.py
file has a variable foo
.
import client
import collection
import database
Then from above the minu directory, the following will work:
from minu.client import foo
Upvotes: 1