You can use relative import

inside env.py, you only need from ..api.models import Base

If you don't want to use relative import, you can also try absolute import like

from be.api.models import Base

provided that you have exported the PYTHONPATH to be by

path_to_be=''
export PYTHONPATH=$path_to_be:$PATH
Answer from meTchaikovsky on Stack Overflow
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 48777391 β€Ί import-parent-directory-package-without-sys-path-append
python - Import parent directory package without sys.path.append - Stack Overflow
February 14, 2018 - @JialiangZhou Unless I'm understanding the meaning of root dictionary incorrectly from parent.sub1 import directoryManager sould work 2018-02-14T00:11:15.26Z+00:00 ... I add the package to python/site-packages but it works in Linux only . In windows, I put is at python27/Lib/site-packages but doesn't work 2018-02-14T00:13:08.247Z+00:00 ... import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from sub1 import directoryManager
Discussions

python - Import file from parent directory causes "Import by filename is not supported" - Stack Overflow
I written a script py-run.py, which ... relative imports without the need for sys.path.append. It achieves this by dynamically constructing the parent module path and running the Python file from the top-level module. This is particularly useful when your script relies on modules located in parent directories and you want ... More on stackoverflow.com
🌐 stackoverflow.com
importing from parent directory
What are you actually trying to accomplish with this? I ask because it sounds like you are trying to do something that is not possible. This is because a submodule cannot be executed independently if it depends on a parent module. In the case you illustrate, foo.py depends on bar.py from a higher level module, so cannot be run on its own. It works with run.py because when you write from L1_dir.L2_dir.foo import *, python will first import the L1_dir module, then resolves the submodule L2_dir and imports that, then resolves the foo submodule and imports that. So in that case, by the time it gets to importing the foo submodule, it has already resolved the parent package and knows this is a child of it so no import error and all dependencies are good to go. You can workaround the import error by not using relative imports but all that is going to happen would be getting another exception indicating the module isn't found. As a side note, I should mention that using from x import * is generally bad practice as it can be unclear what is being imported and has potential for conflicting names. It's not that big of a deal when its only used to reference imports within your own package/module, but I find it's best to just avoid it so as not to get in the habit. More on reddit.com
🌐 r/learnpython
7
2
December 5, 2022
python - Importing modules from parent folder - Stack Overflow
I am running Python 2.5. This is my folder tree: ptdraft/ nib.py simulations/ life/ life.py (I also have __init__.py in each folder, omitted here for readability) How do I import t... More on stackoverflow.com
🌐 stackoverflow.com
Relative Imports
Hello, I am currently on the topic of Relative Imports. My package is set up as shown in the following figure: I have Windows 11 Home, and Python v3.12. I am attempting to import file_2.py and sub_file.py into file_1.py. The script in my file_1.py is as follows: ''' Desktop\pkg\package1\file_1.py ... More on discuss.python.org
🌐 discuss.python.org
5
1
January 14, 2024
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 73420473 β€Ί how-to-import-function-in-parent-folder-without-importing-sys
python - How to import function in parent folder without importing sys? - Stack Overflow
But here is a solution without importing sys (or using PYTHONPATH environment variable - which basically adds the path to the sys.path): change your directory to the parent of root folder.
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί importing from parent directory
r/learnpython on Reddit: importing from parent directory
December 5, 2022 -

This question has been asked so many times but I'm still not finding what I need. If I call `./run.py` everything works fine. Calling `./foo.py` results in ImportError: attempted relative import with no known parent package. The only way I've found to accomplish this is to use sys.path.append which ends up making a mess of my imports. I don't think I want to use setup tools. Is there not some way to just do an absolute import from "package"? e.g. foo.py would have `import package.l1_dir.bar`

package 
|-> run.py 
|-> L1_dir
    |-> __init__.py
    |-> bar.py
    |-> L2_dir    
        |-> __init__.py
        |-> foo.py 

Foo.py

from ..bar import * print("hello from foo.py") 

Bar.py

print("hello from bar.py") 

Run.py

from .L1_dir.L2_dir.foo import *
Top answer
1 of 3
1
What are you actually trying to accomplish with this? I ask because it sounds like you are trying to do something that is not possible. This is because a submodule cannot be executed independently if it depends on a parent module. In the case you illustrate, foo.py depends on bar.py from a higher level module, so cannot be run on its own. It works with run.py because when you write from L1_dir.L2_dir.foo import *, python will first import the L1_dir module, then resolves the submodule L2_dir and imports that, then resolves the foo submodule and imports that. So in that case, by the time it gets to importing the foo submodule, it has already resolved the parent package and knows this is a child of it so no import error and all dependencies are good to go. You can workaround the import error by not using relative imports but all that is going to happen would be getting another exception indicating the module isn't found. As a side note, I should mention that using from x import * is generally bad practice as it can be unclear what is being imported and has potential for conflicting names. It's not that big of a deal when its only used to reference imports within your own package/module, but I find it's best to just avoid it so as not to get in the habit.
2 of 3
1
You can use python -m L1_dir.L2_dir.foo to execute it. However I'd advise to move your executable logic to a separate file, and do not use relative imports in that file. If the directory containing package is on the PYTHONPATH (sys.path), then you can write import package.L1_dir.bar from any file. The "correct" way to do this is to install the package via setuptools. If you use setuptools, you could also define an entrypoint; you can execute that entrypoint command from anywhere. IIRC it internally uses the -m semantics so shouldn't require extra sys.path or PYTHONPATH shenanigans.
Top answer
1 of 2
760

You could use relative imports (Python >= 2.5):

from ... import nib

(What’s New in Python 2.5) PEP 328: Absolute and Relative Imports

2 of 2
562

I posted a similar answer also to the question regarding imports from sibling packages. You can see it here.

Solution without sys.path hacks

Summary

  • Wrap the code into one folder (e.g. packaged_stuff)
  • Create a pyproject.toml (older alternative: setup.py)
  • Pip install the package in editable state with pip install -e <myproject_folder>
  • Import using from packaged_stuff.modulename import function_name

Setup

I assume the same folder structure as in the question

.
└── ptdraft
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ nib.py
    └── simulations
        β”œβ”€β”€ __init__.py
        └── life
            β”œβ”€β”€ __init__.py
            └── life.py

I call the . the root folder, and in my case it is located in C:\tmp\test_imports.

Steps


1) Add a pyproject.toml to the root folder

The contents of the pyproject.toml can be simply

[project]
name = "ptdraft"
version = "0.1.0"
description = "My small project"

[build-system]
build-backend = "flit_core.buildapi"
requires = ["flit_core >=3.2,<4"]

Basically "any" valid pyproject.toml would work. This is just a minimal working example, which uses flit as build backend.


2) Use a virtual environment

If you are familiar with virtual environments, activate one, and skip to the next step. Usage of virtual environments are not absolutely required, but they will really help you out in the long run (when you have more than 1 project ongoing..). The most basic steps are (run in the root folder)

  • Create virtual env
    • python -m venv venv
  • Activate virtual env
    • . venv/bin/activate (Linux) or ./venv/Scripts/activate (Win)
  • Deactivate virtual env
    • deactivate (Linux)

To learn more about this, just Google out "python virtualenv tutorial" or similar. You probably never need any other commands than creating, activating and deactivating.

Once you have made and activated a virtual environment, your console should give the name of the virtual environment in parenthesis

PS C:\tmp\test_imports> python -m venv venv
PS C:\tmp\test_imports> .\venv\Scripts\activate
(venv) PS C:\tmp\test_imports>

3) pip install your project in editable state

Install your top level package (here ptdraft) using pip. The trick is to use the -e flag when doing the install. This way it is installed in an editable state, and all the edits made to the .py files will be automatically included in the installed package. Note that the -e flag with pyproject.toml requires pip 21.3 or newer.

In the root directory, run

pip install -e . (note the dot, it stands for "current directory")

You can also see that it is installed by using pip freeze

(venv) PS C:\tmp\test_imports> pip install -e .
Obtaining file:///home/user/projects/ptdraft
  Installing build dependencies ... done
  Checking if build backend supports build_editable ... done
  Getting requirements to build editable ... done
  Preparing editable metadata (pyproject.toml) ... done
....
Successfully built ptdraft
Installing collected packages: ptdraft
Successfully installed ptdraft-0.1.0
(venv) PS C:\tmp\test_imports> pip freeze
ptdraft==0.1.0

4) Import by prepending mainfolder to every import

In this example, the mainfolder would be ptdraft. This has the advantage that you will not run into name collisions with other module names (from python standard library or 3rd party modules).


Example Usage

nib.py

def function_from_nib():
    print('I am the return value from function_from_nib!')

life.py

from ptdraft.nib import function_from_nib

if __name__ == '__main__':
    function_from_nib()

Running life.py

(venv) PS C:\tmp\test_imports> python .\ptdraft\simulations\life\life.py
I am the return value from function_from_nib!
🌐
FavTutor
favtutor.com β€Ί blogs β€Ί import-from-parent-directory-python
How to Import File from Parent Directory in Python? (with code)
November 17, 2023 - Consider a scenario where you have a directory structure with a main script in the parent directory and a subdirectory containing additional Python files. If you try to import a module from the parent directory directly, you may encounter an ImportError or ModuleNotFoundError. However, there are several techniques and workarounds that can be used to import files and modules from the parent directory. These techniques involve modifying the sys.path variable, leveraging environment variables, and using relative imports.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί python-import-from-parent-directory
Python - Import from parent directory - GeeksforGeeks
August 21, 2024 - File "C:/Users/sai mohan pulamolu/Desktop/parentdirectory/subdirectory/temp.py", line 2, in <module> ... In order to import a module, the directory having that module must be present on PYTHONPATH.
🌐
Enterprise DNA
blog.enterprisedna.co β€Ί python-import-from-parent-directory
Enterprise DNA: We Help Businesses Put Data and AI to Work
Learn data and AI skills on the platform, bring us in on a project, or run a managed Omni Command Centre. 220K+ professionals trained, 1,500+ companies impacted globally.
🌐
Buggy Programmer
buggyprogrammer.com β€Ί home β€Ί how to import module from parent directory in python in 2022?
How To Import Module From Parent Directory In Python In 2022? - Buggy Programmer
July 8, 2022 - The first and foremost method which you can use is to add the file path as an argument in the sys.path.append() function which will add the parent directory into the default workspace or the PYTHONPATH of your python environment and you can ...
🌐
Delft Stack
delftstack.com β€Ί "delft stack" β€Ί "howto" β€Ί "python how-to's" β€Ί "how to import modules from parent directory in python"
How to Import Modules From Parent Directory in Python | Delft Stack
March 11, 2025 - Module parent_module imported successfully. By setting the PYTHONPATH, you inform Python where to look for modules, including those in parent directories. This method is advantageous because it allows you to keep your code clean without modifying sys.path.
🌐
Python.org
discuss.python.org β€Ί python help
Relative Imports - Python Help - Discussions on Python.org
Hello, I am currently on the topic of Relative Imports. My package is set up as shown in the following figure: I have Windows 11 Home, and Python v3.12. I am attempting to import file_2.py and sub_file.py into file_1.py. The script in my file_1.py is as follows: ''' Desktop\pkg\package1\file_1.py ''' ''' Action Desired: Import file_2.py and sub_file.py ''' from . import file_2 from .sub_package import sub_file num1 = 11 string1 = "I'm in package1, file_1." def run_1(message)...
Published: January 14, 2024
🌐
Syntx Scenarios
syntaxscenarios.com β€Ί home β€Ί python β€Ί how to import from parent directory in python? (top 6 ways)
How to Import from Parent Directory in Python? (Top 6 Ways)
August 16, 2026 - Problem? Python doesn’t automatically search the parent folder of script.py. That’s why you need special methods to import the file. When you write import module_name, Python searches for that module in: The current script’s directory. The directories listed in sys.path.
🌐
Codemia
codemia.io β€Ί home β€Ί knowledge hub β€Ί importing modules from parent folder
Importing modules from parent folder | Codemia
January 2, 2025 - If your folders are structured as packages (each folder has an __init__.py file), you can use relative imports: ... This method is more consistent with Python's own recommendations and works especially well when you're developing packages. While modifying sys.path can quickly solve the problem, it's generally better to structure your projects in a way that major dependencies are placed in subdirectories rather than parent directories, or to use package-relative imports.
🌐
Sentry
sentry.io β€Ί sentry answers β€Ί python β€Ί import files from a different folder in python
Python Import From Parent Directory and Subfolders | Sentry
To import scripts from parent or sibling directories, we can use package relative imports. First, we must ensure that our directories are recognized as packages by Python, which we can do by creating an empty file named __init__.py in each of them.
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί import from parent directory
r/learnpython on Reddit: Import from parent directory
September 5, 2022 -

Hello there :)

Assume, you have the following file structure:

.

└── a

β”œβ”€β”€ a_file.py

└── b

└── b_file.py

In b_file, I want to import functions from a_file. Even adding __init__.py to a/ did not help.

When searching for the problem, I found that I seemingly had to add b/ to PYTHONPATH or whatever. Please tell me there is a more convenient solution.

(If there's not a nice and simple solution, I'd be really interested in why it is not possible to simply import from a parent folder while it is no problem to import from a child directory.)

🌐
Tutor Python
tutorpython.com β€Ί python-import-from-parent-directory
Python Import from parent directory - Tutor Python
October 19, 2023 - Python’s import system allows developers to make use of functionality defined within other modules in order to enhance their projects. By default, however, we can only carry out import if the modules we seek are in the same directory as the running module. What if we want to import from a different directory? Specifically, How can we import from the parent ...
🌐
GitHub
gist.github.com β€Ί iglpdc β€Ί ebb9beb8596ddc18b0e5bae03524c18e
Import modules from parent folder in Python Β· GitHub
Import modules from parent folder in Python. GitHub Gist: instantly share code, notes, and snippets.
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί how can i import code from the parent directory into my notebook?
r/learnpython on Reddit: How can I import code from the parent directory into my notebook?
October 14, 2022 -

I am having the classic problem with my imports. I know that this is a very common issue to run into and I am still trying to understand it, but I could use a little help.

I have a package:

.
β”œβ”€β”€ my_package
β”‚   β”œβ”€β”€ main.py
β”‚   β”œβ”€β”€ notebooks
β”‚   β”‚   └── notebook.ipynb
β”‚   └── utils.py
└── some_file.txt

The code is mostly in main.py, which imports utils.py for some helpers. But since I am also exploring certain things before properly developing in main.py, I have also a notebooks directory. Inside here I play around with a bunch of stuff and this requires access to the code from main, utils, etc.

My problem is that I cannot import those code. If I type, from my_package import utils I receive a ModuleNotFoundError: No module named 'my_package'. If I run a from .. import utils I receive ImportError: attempted relative import with no known parent package.

Am I correct in saying that the only proper way to do this is to make a proper setup with setup.py and $ pip install -e my_package? I do not like using sys to update the path, it seems dirty. If there is a way to do this without the setup then that would be great, as wasn't intending to make it a full package as it is only a small project and I am learning.

[edit] It seems that the "proper" way would be to go with the setup.py approach, but I just found a way to update the conda environment to include this permanently which is a decent solution. Just needed to type $ conda develop path/to/my_project and it creates a conda.pth file in the conda environment's site-packages directory.