ACB
ACB

Reputation: 121

Import python module from different folder

I have a solution with different folders and I wanted to create a common package for them to share reusable code. There are lot of examples for python packages are there. None of them addresses separate folder scenario in a simple way.

My folder structure is :

Client/
    __init__.py
    --logic.py
Common/
    __init__.py
    -- Constants.py
Server/
    __init__.py
    -- Test.py

My Test.py looks like this :

from Common import Constant        
print(Constant.TEST_VALUE)  #-- From common package

But the code not even passes the import statements.

Exception has occurred: ModuleNotFoundError No module named 'Common'

If I try with relative path : from ..Common import Constant

Error:

Exception has occurred: ImportError attempted relative import with no known parent package

My purpose is to reuse the constant.py file for both Cars and Server solution. There are examples for sys.path which I am not sure if its a good practice. Also the code in Common will not be having complex codes to proceed with installing them.

Upvotes: 0

Views: 1667

Answers (2)

Karl Knechtel
Karl Knechtel

Reputation: 61479

If these packages are meant to be part of the same conceptual project, then simply make a containing package. Now the relative import will work as long as you start from outside the package hierarchy, and ensure the containing folder is on sys.path. The easy ways to do that are to install the package (preferably to a virtual environment), or start python from that folder (in which case Cars, Common and Server appear as separate packages) or just outside (in which case the containing folder is a package and Cars, Common and Server are sub-packages - which is probably what you want; it's more consistent with how you will most likely install the code later).

If these packages are separate projects that happen to depend upon one another, then Python has no reason by default to look in any particular place for the dependency packages - aside from the places it ordinarily looks for anything. So, again, you can start python from the containing folder if there actually is such a containing folder; but there isn't a good project-organization reason for there to be a containing folder - so set up an actual project for each package, and install them all to the same virtual environment. Now you can do cross-package imports with absolute syntax (but not relative syntax, because that only works within a package hierarchy).

Upvotes: 1

oflint_
oflint_

Reputation: 297

You can use this code found here:

# Test.py
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '/path/to/Cars/')
sys.path.insert(1, '/path/to/Common/')

import Audi
import Constants

Upvotes: 0

Related Questions