Let's have MyClass in module.name module defined at /path/to/file.py. Below is how we import MyClass from this module

For Python 3.5+ use (docs):

import importlib.util
import sys
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
sys.modules["module.name"] = foo
spec.loader.exec_module(foo)
foo.MyClass()

For Python 3.3 and 3.4 use:

from importlib.machinery import SourceFileLoader

foo = SourceFileLoader("module.name", "/path/to/file.py").load_module()
foo.MyClass()

(Although this has been deprecated in Python 3.4.)

For Python 2 use:

import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

There are equivalent convenience functions for compiled Python files and DLLs.

See also http://bugs.python.org/issue21436.

Answer from Sebastian Rittau on Stack Overflow
🌐
Real Python
realpython.com › ref › glossary › import-path
import path | Python Glossary – Real Python
In Python, the import path refers to the list of locations (path entries) that Python’s path-based finder searches to find the modules you want to import.
🌐
Python
docs.python.org › 3 › library › pathlib.html
pathlib — Object-oriented filesystem paths
>>> from pathlib import Path · Listing subdirectories: >>> p = Path('.') >>> [x for x in p.iterdir() if x.is_dir()] [PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'), PosixPath('__pycache__'), PosixPath('build')] Listing Python source ...
Discussions

What is the best way to import a module from a path?
It's probably the responsibility of the script that boots your python script to set PYTHONPATH. From the perspective of python, make sure the environment is set up correctly before the interpreter boots up. In other words, don't do this! More on reddit.com
🌐 r/learnpython
28
66
November 14, 2019
python - How can I import a module dynamically given the full path? - Stack Overflow
How do I load a Python module given its full path? Note that the file can be anywhere in the filesystem where the user has access rights. See also: How to import a module given its name as string? More on stackoverflow.com
🌐 stackoverflow.com
python - Import paths - the right way? - Stack Overflow
I know there are A LOT of similar or the same questions, but i still cannot understand / find the right way for me to work with modules. Python is my favorite language, and i like everything in it ... More on stackoverflow.com
🌐 stackoverflow.com
Import files directly from file location - Ideas - Discussions on Python.org
Importing new modules in Python is a pain, and far from straightforward. The trivial way to import a new module would be to give the full path of the file containing the required code - which could be a python __init__ module itself, setting up a fully functional module. More on discuss.python.org
🌐 discuss.python.org
0
July 25, 2023
🌐
Chris Yeh
chrisyeh96.github.io › 2017 › 08 › 08 › definitive-guide-python-imports.html
The Definitive Guide to Python import Statements | Chris Yeh
August 8, 2017 - For example, since packB lacks a __init__.py file, calling import packB (in Python 3.3+) has very little use because no objects in the packB package are made available. A subsequent call to packB.b1 would fail because it has not been imported yet. An absolute import uses the full path (starting from the project’s root folder) to the desired module to import.
🌐
Python for the Lab
pythonforthelab.com › blog › complete-guide-to-imports-in-python-absolute-relative-and-more
Complete Guide to Imports in Python: Absolute, Relative, and More | Python For The Lab
The same problem will appear if we trigger python from any other location in the computer: ... What we did in the examples above is called absolute imports. It means that we specify the full path to the module we want to import. What we have to remember is that the folder from which you trigger Python is the first place where the program looks for modules.
🌐
GeeksforGeeks
geeksforgeeks.org › python › pathlib-module-in-python
Pathlib Module in Python - GeeksforGeeks
It returns True if the path exists, otherwise False. Example: This code checks whether the given path exists. ... from pathlib import Path path = '/home/hrithik/Desktop' obj = Path(path) # Create Path object print(obj.exists())
Published: June 15, 2026
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-import-a-python-module-given-the-full-path
How to import a Python module given the full path? - GeeksforGeeks
July 23, 2025 - This is the easiest way to import a Python module by adding the module path to the path variable.
🌐
pytest
docs.pytest.org › en › stable › explanation › pythonpath.html
pytest import mechanisms and sys.path/PYTHONPATH - pytest documentation
Importing files in Python is a non-trivial process, so aspects of the import process can be controlled through the --import-mode command-line flag, which can assume these values: prepend (default): The directory path containing each module will be inserted into the beginning of sys.path if not already there, and then imported with the importlib.import_module function.
🌐
W3Schools
w3schools.com › python › ref_module_pathlib.asp
Python pathlib Module
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training · ❮ Standard Library Modules · Work with paths using objects instead of strings: from pathlib import Path p = Path("/home/user") / "projects" / "demo.txt" print(p.name) print(p.parent) print(p.suffix) Try it Yourself » ·
Top answer
1 of 3
42

What is the entry point for your program? Usually the entry point for a program will be at the root of the project. Since it is at the root, all the modules within the root will be importable, provided there is an __init__.py file in them.

So, using your example:

my_project/
    main.py
    package1/
        __init__.py
        module1
        module2
    package2/
        __init__.py
        module1
        module2

main.py would be the entry point for your program. Because the file that is executed as main is automatically put on the PYTHONPATH, both package1 and package2 are available from the top level import.

# in main.py
from package1.module1 import *
from package1.module2 import *

# in package1.module1
import module2
from package2.module1 import *

# in package2.module1 import *
import module2
from package1.module1 import *

Note that in the above, package1 and package2 depend on each other. That should never be the case. But this is just an example of being able to import from anywhere.

main.py doesn't have to be anything fancy either. It can be very simple:

# main.py

if __name__ == '__main__':
    from package1.module1 import SomeClass
    SomeClass().start()

The point I'm trying to make, is that if a module needs to be accessible by other modules, that module should be available as a top level import. A module should not attempt to put itself as a top level import (directly on the PYTHONPATH).

It should be the responsibility of the project for ensuring that all imports can be satisfied if the module is included directly in the project. There are two ways to do this. The first is by creating a bootstrapper file such as main.py in the project folder. The other, is by creating a file that adds all relevant paths to PYTHONPATH, that is loaded by any entry points that may exist.

For example:

# setup.py
import sys

def load():
    paths = ['/path1/','/path2/','/path3/']
    for p in path:
        sys.path.insert(0, p)

# entrypoint.py
from setup import load
load()
# continue with program

The main thing to take away, is that a module is not supposed to put itself on the path. The path should be determined automatically by the entry point into the program, or defined explicitly by a setup script that knows where all the relevant modules are.

2 of 3
6

I generally create each package as an installable package (ie, create a setup.py file), and then install them into a virtualenv just for this project, using pip.

You can even install the using pip -e if they are still under development.

🌐
Python.org
discuss.python.org › ideas
Import files directly from file location - Ideas - Discussions on Python.org
July 25, 2023 - The trivial way to import a new module would be to give the full path of the file containing the required code - which could be a python __init__ module itself, setting up a fully functional module.
Top answer
1 of 3
228

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 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.

2 of 3
13

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 !

🌐
Medium
medium.com › @jameskabbes › importing-your-local-package-with-pythonpath-c459dc209c7
Importing your Local Package with PYTHONPATH | by James Kabbes | Medium
September 21, 2023 - >>> import sys >>> sys.path.append( '/path/to/parent_of_test_package' ) >>> import test_package >>> Let’s add to our package before moving along. This is a special file for Python packages.
🌐
Zean
zean.be › articles › definitive-guide-python-imports
The definitive guide to Python import statements - Zean Qin
For example, since packB lacks ... A subsequent call to packB.b1 would fail because it has not been imported yet. An absolute import uses the full path (starting from the project's root folder) to the desired module to import....
🌐
Python documentation
docs.python.org › 3 › reference › import.html
5. The import system — Python 3.15.2 documentation
When the import system searches a regular package’s __path__ and encounters a subdirectory that does not contain an __init__.py file, that subdirectory becomes a portion contributing to a namespace subpackage of the enclosing regular package. See also PEP 420 for the namespace package specification. To begin the search, Python needs the fully qualified name of the module (or package, but for the purposes of this discussion, the difference is immaterial) being imported.
Top answer
1 of 3
171

How python finds its modules

Strictly taken, a module is a single python file, while a package is a folder containing python files, accompanied by a (can be empty) file named __init__.py, to tell python it is a package to import modules from. In both cases, modules need their .py extension, but importing them is done without (see further below).

By default, Python looks for its modules and packages in $PYTHONPATH.

To find out what is included in $PYTHONPATH, run the following code in python (3):

import sys
print(sys.path)

How to add a directory

Occasionally

From within a python file, you can add path(s) occasionally to the default path by adding the following lines in the head section of your python application or script:

import sys
sys.path.insert(0, "/path/to/your/package_or_module")

For example:

if I have a folder: /home/myname/pythonfiles, and I want to import the file module_1.py, located in that directory, I add this to the head section of my code:

import sys
sys.path.insert(0, "/home/myname/pythonfiles")

And I can simply import the file module_1.py by:

import module_1

When I create a package and want to import module(s) from the package, I need to create a folder in $PYTHONPATH, containing the modules, accompanied by a (can be empty) file called __init__.py

For example:

To import from a package (folder) called my_package in /home/myname/pythonfiles , add the /home/myname/pythonfiles path to your $PYTHONPATH, like in example 1, and import the module called module_2.py (inside the package folder) simply with: `

from <packagename> import module_2

Adding directories to $PYTHONPATH permanently:

Add the following line to your ~/.profile file.

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

Subdirectories

From within a package, subdirectories are not included just like that; you need to "chain" the directories. To import a module module_3.py, inside folder subfolder inside folder packagename:

import packagename.subfolder.module_3

Given the fact that all subfolders in the package include their own __init__.py file.

When a module is in the same directory as the script or application

There is no need to insert the path to a module when it is in the same directory as the script or application, it is automatically added.

Example:

If I have a folder, containing script.py and module.py, I can simply import the module by:

import module
2 of 3
7

The correct way to use relative import is:

from ..Common import foo1

And you also need a __init__.py in all your folders.

🌐
Plain English
python.plainenglish.io › python-imports-a-guide-to-packages-modules-and-paths-d51561bf56bb
Python Imports: A Guide to Packages, Modules, and Paths | by Gaurav Garg | Python in Plain English
November 27, 2023 - In Python, the PYTHONPATH environment variable is used to specify the search path for modules and packages. When Python imports a module or package, it searches for it in the directories listed in the PYTHONPATH variable.
Top answer
1 of 2
95

This will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are doing is generally correct.

set.py:

import sys
sys.path.append("/tmp/TEST")

loop.py

import sys
import time
while True:
  print sys.path
  time.sleep(1)

run: python loop.py &

This will run loop.py, connected to your STDOUT, and it will continue to run in the background. You can then run python set.py. Each has a different set of environment variables. Observe that the output from loop.py does not change because set.py does not change loop.py's environment.

A note on importing

Python imports are dynamic, like the rest of the language. There is no static linking going on. The import is an executable line, just like sys.path.append....

2 of 2
9

As also noted in the docs here.

Go to Python X.Y/Lib (Windows) or /usr/lib/pythonX.Y (Linux) and add these lines to the site.py there,

import sys
sys.path.append("yourpathstring")

This changes your sys.path so that on every load, it will have that value in it..

As stated here about site.py,

This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.

For other possible methods of adding some path to sys.path see these docs