I have a folder for my client code, a folder for my server code, and a folder for code that is shared between them
Proj/
Client/
Client.py
Server/
Server.py
Common/
__init__.py
Common.py
How do I import Common.py from Server.py and Client.py?
Doing a relative import is absolulutely OK! Here's what little 'ol me does:
Funny enough, a same problem I just met, and I get this work in following way:
combining with linux command
ln
, we can make thing a lot simper:And, now if you want to import
some_stuff
from file:Proj/Common/Common.py
into your file:Proj/Client/Client.py
, just like this:And, the same applies to
Proj/Server
, Also works forsetup.py
process, a same question discussed here, hope it helps !The default import method is already "relative", from the PYTHONPATH. The PYTHONPATH is by default, to some system libraries along with the folder of the original source file. If you run with -m to run a module, the current directory gets added to the PYTHONPATH. So if the entry point of your program is inside of Proj, then using
import Common.Common
should work inside both Server.py and Client.py.Don't do a relative import. It won't work how you want it to.
EDIT Nov 2014 (3 years later):
Python 2.6 and 3.x supports proper relative imports, where you can avoid doing anything hacky. With this method, you know you are getting a relative import rather than an absolute import. The '..' means, go to the directory above me:
As a caveat, this will only work if you run your python as a module, from outside of the package. For example:
Original hacky way
You can add Common/ to your sys.path (the list of paths python looks at to import things):
os.path.dirname(__file__)
just gives you the directory that your current python file is in, and then we navigate to 'Common/' the directory and import 'Common' the module.Don't do relative import.
From PEP8:
Put all your code into one super package (i.e. "myapp") and use subpackages for client, server and common code.
Update: "Python 2.6 and 3.x supports proper relative imports (...)". See Dave's answers for more details.