Importing from a relative path in Python

Importing from a relative path in Python

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:

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

Original hacky way

This method is still commonly used in some situations, where you arent actually ever installing your package. For example, its 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/ into your file: Proj/Client/, just like this:

# in Proj/Client/
from Common.Common import some_stuff

And, the same applies to Proj/Server, Also works for process,
a same question discussed here, hope it helps !

Importing from a relative path in Python

Dont do relative import.

From PEP8:

Relative imports for intra-package imports are highly discouraged.

Put all your code into one super package (i.e. myapp) and use subpackages for client, server and common code.

Python 2.6 and 3.x supports proper relative imports (…). See Daves answers for more details.

Leave a Reply

Your email address will not be published. Required fields are marked *