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?
Relative imports make use of dot notation to specify location. A single dot means that the module or package referenced is in the same directory as the current location. Two dots mean that it is in the parent directory of the current location—that is, the directory above.
A relative path starts with / , ./ or ../ . To get a relative path in Python you first have to find the location of the working directory where the script or module is stored. Then from that location, you get the relative path to the file want.
To get an absolute path in Python you use the os. path. abspath library. Insert your file name and it will return the full path relative from the working directory including the file.
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:
from ..Common import Common
As a caveat, this will only work if you run your python as a module, from outside of the package. For example:
python -m Proj
This method is still commonly used in some situations, where you aren't actually ever 'installing' your package. For example, it's popular with Django users.
You can add Common/ to your sys.path (the list of paths python looks at to import things):
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'Common'))
import Common
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.
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:
1. cd Proj/Client
2. ln -s ../Common ./
3. cd Proj/Server
4. ln -s ../Common ./
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:
# in Proj/Client/Client.py
from Common.Common import some_stuff
And, the same applies to Proj/Server
, Also works for setup.py
process,
a same question discussed here, hope it helps !
Doing a relative import is absolulutely OK! Here's what little 'ol me does:
#first change the cwd to the script path
scriptPath = os.path.realpath(os.path.dirname(sys.argv[0]))
os.chdir(scriptPath)
#append the relative location you want to import from
sys.path.append("../common")
#import your module stored in '../common'
import common.py
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With