unfortunately, this module needs to be inside the package, and it also needs to be runnable as a script, sometimes. Any idea how I could achieve that?

It's quite common to have a layout like this...

main.py
mypackage/
    __init__.py
    mymodule.py
    myothermodule.py

...with a mymodule.py like this...

#!/usr/bin/env python3

# Exported function
def as_int(a):
    return int(a)

# Test function for module  
def _test():
    assert as_int('1') == 1

if __name__ == '__main__':
    _test()

...a myothermodule.py like this...

#!/usr/bin/env python3

from .mymodule import as_int

# Exported function
def add(a, b):
    return as_int(a) + as_int(b)

# Test function for module  
def _test():
    assert add('1', '1') == 2

if __name__ == '__main__':
    _test()

...and a main.py like this...

#!/usr/bin/env python3

from mypackage.myothermodule import add

def main():
    print(add('1', '1'))

if __name__ == '__main__':
    main()

...which works fine when you run main.py or mypackage/mymodule.py, but fails with mypackage/myothermodule.py, due to the relative import...

from .mymodule import as_int

The way you're supposed to run it is...

python3 -m mypackage.myothermodule

...but it's somewhat verbose, and doesn't mix well with a shebang line like #!/usr/bin/env python3.

The simplest fix for this case, assuming the name mymodule is globally unique, would be to avoid using relative imports, and just use...

from mymodule import as_int

...although, if it's not unique, or your package structure is more complex, you'll need to include the directory containing your package directory in PYTHONPATH, and do it like this...

from mypackage.mymodule import as_int

...or if you want it to work "out of the box", you can frob the PYTHONPATH in code first with this...

import sys
import os

SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.dirname(SCRIPT_DIR))

from mypackage.mymodule import as_int

It's kind of a pain, but there's a clue as to why in an email written by a certain Guido van Rossum...

I'm -1 on this and on any other proposed twiddlings of the __main__ machinery. The only use case seems to be running scripts that happen to be living inside a module's directory, which I've always seen as an antipattern. To make me change my mind you'd have to convince me that it isn't.

Whether running scripts inside a package is an antipattern or not is subjective, but personally I find it really useful in a package I have which contains some custom wxPython widgets, so I can run the script for any of the source files to display a wx.Frame containing only that widget for testing purposes.

Answer from Aya on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › importerror: attempted relative import with no known parent package
r/learnpython on Reddit: ImportError: attempted relative import with no known parent package
July 9, 2022 -

Hi all!

Say I have this folderstructure:

package
├── __init__.py
├── module.py
└── subpackage
    ├── bar.py
    ├── __init__.py
    └── subsubpackage
        ├── __init__.py
        └── foo.py

And I would like to import a function called 'func' from 'bar.py' into 'foo.py. How would I do this?

I tried literally every combination possible...like:

from .bar import func

from subpackage.bar import func

from ..bar import func

from . import bar.func

Problem is....nothing works, as I always get this error:

ImportError: attempted relative import with no known parent package

When I read on stackoverflow, I read a lot of different answers, most of them involving manipulating sys.path and quite complex.

I dont really understand why such a simple thing would be so complicated...what am I missing here?

Top answer
1 of 16
1444

unfortunately, this module needs to be inside the package, and it also needs to be runnable as a script, sometimes. Any idea how I could achieve that?

It's quite common to have a layout like this...

main.py
mypackage/
    __init__.py
    mymodule.py
    myothermodule.py

...with a mymodule.py like this...

#!/usr/bin/env python3

# Exported function
def as_int(a):
    return int(a)

# Test function for module  
def _test():
    assert as_int('1') == 1

if __name__ == '__main__':
    _test()

...a myothermodule.py like this...

#!/usr/bin/env python3

from .mymodule import as_int

# Exported function
def add(a, b):
    return as_int(a) + as_int(b)

# Test function for module  
def _test():
    assert add('1', '1') == 2

if __name__ == '__main__':
    _test()

...and a main.py like this...

#!/usr/bin/env python3

from mypackage.myothermodule import add

def main():
    print(add('1', '1'))

if __name__ == '__main__':
    main()

...which works fine when you run main.py or mypackage/mymodule.py, but fails with mypackage/myothermodule.py, due to the relative import...

from .mymodule import as_int

The way you're supposed to run it is...

python3 -m mypackage.myothermodule

...but it's somewhat verbose, and doesn't mix well with a shebang line like #!/usr/bin/env python3.

The simplest fix for this case, assuming the name mymodule is globally unique, would be to avoid using relative imports, and just use...

from mymodule import as_int

...although, if it's not unique, or your package structure is more complex, you'll need to include the directory containing your package directory in PYTHONPATH, and do it like this...

from mypackage.mymodule import as_int

...or if you want it to work "out of the box", you can frob the PYTHONPATH in code first with this...

import sys
import os

SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.dirname(SCRIPT_DIR))

from mypackage.mymodule import as_int

It's kind of a pain, but there's a clue as to why in an email written by a certain Guido van Rossum...

I'm -1 on this and on any other proposed twiddlings of the __main__ machinery. The only use case seems to be running scripts that happen to be living inside a module's directory, which I've always seen as an antipattern. To make me change my mind you'd have to convince me that it isn't.

Whether running scripts inside a package is an antipattern or not is subjective, but personally I find it really useful in a package I have which contains some custom wxPython widgets, so I can run the script for any of the source files to display a wx.Frame containing only that widget for testing purposes.

2 of 16
711

Explanation

From PEP 328

Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

At some point PEP 338 conflicted with PEP 328:

... relative imports rely on __name__ to determine the current module's position in the package hierarchy. In a main module, the value of __name__ is always '__main__', so explicit relative imports will always fail (as they only work for a module inside a package)

and to address the issue, PEP 366 introduced the top level variable __package__:

By adding a new module level attribute, this PEP allows relative imports to work automatically if the module is executed using the -m switch. A small amount of boilerplate in the module itself will allow the relative imports to work when the file is executed by name. [...] When it [the attribute] is present, relative imports will be based on this attribute rather than the module __name__ attribute. [...] When the main module is specified by its filename, then the __package__ attribute will be set to None. [...] When the import system encounters an explicit relative import in a module without __package__ set (or with it set to None), it will calculate and store the correct value (__name__.rpartition('.')[0] for normal modules and __name__ for package initialisation modules)

(emphasis mine)

If the __name__ is '__main__', __name__.rpartition('.')[0] returns empty string. This is why there's empty string literal in the error description:

SystemError: Parent module '' not loaded, cannot perform relative import

The relevant part of the CPython's PyImport_ImportModuleLevelObject function:

if (PyDict_GetItem(interp->modules, package) == NULL) {
    PyErr_Format(PyExc_SystemError,
            "Parent module %R not loaded, cannot perform relative "
            "import", package);
    goto error;
}

CPython raises this exception if it was unable to find package (the name of the package) in interp->modules (accessible as sys.modules). Since sys.modules is "a dictionary that maps module names to modules which have already been loaded", it's now clear that the parent module must be explicitly absolute-imported before performing relative import.

Note: The patch from the issue 18018 has added another if block, which will be executed before the code above:

if (PyUnicode_CompareWithASCIIString(package, "") == 0) {
    PyErr_SetString(PyExc_ImportError,
            "attempted relative import with no known parent package");
    goto error;
} /* else if (PyDict_GetItem(interp->modules, package) == NULL) {
    ...
*/

If package (same as above) is empty string, the error message will be

ImportError: attempted relative import with no known parent package

However, you will only see this in Python 3.6 or newer.

Solution #1: Run your script using -m

Consider a directory (which is a Python package):

.
├── package
│   ├── __init__.py
│   ├── module.py
│   └── standalone.py

All of the files in package begin with the same 2 lines of code:

from pathlib import Path
print('Running' if __name__ == '__main__' else 'Importing', Path(__file__).resolve())

I'm including these two lines only to make the order of operations obvious. We can ignore them completely, since they don't affect the execution.

__init__.py and module.py contain only those two lines (i.e., they are effectively empty).

standalone.py additionally attempts to import module.py via relative import:

from . import module  # explicit relative import

We're well aware that /path/to/python/interpreter package/standalone.py will fail. However, we can run the module with the -m command line option that will "search sys.path for the named module and execute its contents as the __main__ module":

vaultah@base:~$ python3 -i -m package.standalone
Importing /home/vaultah/package/__init__.py
Running /home/vaultah/package/standalone.py
Importing /home/vaultah/package/module.py
>>> __file__
'/home/vaultah/package/standalone.py'
>>> __package__
'package'
>>> # The __package__ has been correctly set and module.py has been imported.
... # What's inside sys.modules?
... import sys
>>> sys.modules['__main__']
<module 'package.standalone' from '/home/vaultah/package/standalone.py'>
>>> sys.modules['package.module']
<module 'package.module' from '/home/vaultah/package/module.py'>
>>> sys.modules['package']
<module 'package' from '/home/vaultah/package/__init__.py'>

-m does all the importing stuff for you and automatically sets __package__, but you can do that yourself in the

Solution #2: Set __package__ manually

Please treat it as a proof of concept rather than an actual solution. It isn't well-suited for use in real-world code.

PEP 366 has a workaround to this problem, however, it's incomplete, because setting __package__ alone is not enough. You're going to need to import at least N preceding packages in the module hierarchy, where N is the number of parent directories (relative to the directory of the script) that will be searched for the module being imported.

Thus,

  1. Add the parent directory of the Nth predecessor of the current module to sys.path

  2. Remove the current file's directory from sys.path

  3. Import the parent module of the current module using its fully-qualified name

  4. Set __package__ to the fully-qualified name from 2

  5. Perform the relative import

I'll borrow files from the Solution #1 and add some more subpackages:

package
├── __init__.py
├── module.py
└── subpackage
    ├── __init__.py
    └── subsubpackage
        ├── __init__.py
        └── standalone.py

This time standalone.py will import module.py from the package package using the following relative import

from ... import module  # N = 3

We'll need to precede that line with the boilerplate code, to make it work.

import sys
from pathlib import Path

if __name__ == '__main__' and __package__ is None:
    file = Path(__file__).resolve()
    parent, top = file.parent, file.parents[3]

    sys.path.append(str(top))
    try:
        sys.path.remove(str(parent))
    except ValueError: # Already removed
        pass

    import package.subpackage.subsubpackage
    __package__ = 'package.subpackage.subsubpackage'

from ... import module # N = 3

It allows us to execute standalone.py by filename:

vaultah@base:~$ python3 package/subpackage/subsubpackage/standalone.py
Running /home/vaultah/package/subpackage/subsubpackage/standalone.py
Importing /home/vaultah/package/__init__.py
Importing /home/vaultah/package/subpackage/__init__.py
Importing /home/vaultah/package/subpackage/subsubpackage/__init__.py
Importing /home/vaultah/package/module.py

A more general solution wrapped in a function can be found here. Example usage:

if __name__ == '__main__' and __package__ is None:
    import_parents(level=3) # N = 3

from ... import module
from ...module.submodule import thing

Solution #3: Use absolute imports and setuptools

The steps are -

  1. Replace explicit relative imports with equivalent absolute imports

  2. Install package to make it importable

For instance, the directory structure may be as follows

.
├── project
│   ├── package
│   │   ├── __init__.py
│   │   ├── module.py
│   │   └── standalone.py
│   └── setup.py

where setup.py is

from setuptools import setup, find_packages
setup(
    name = 'your_package_name',
    packages = find_packages(),
)

The rest of the files were borrowed from the Solution #1.

Installation will allow you to import the package regardless of your working directory (assuming there'll be no naming issues).

We can modify standalone.py to use this advantage (step 1):

from package import module  # absolute import

Change your working directory to project and run /path/to/python/interpreter setup.py install --user (--user installs the package in your site-packages directory) (step 2):

vaultah@base:~$ cd project
vaultah@base:~/project$ python3 setup.py install --user

Let's verify that it's now possible to run standalone.py as a script:

vaultah@base:~/project$ python3 -i package/standalone.py
Running /home/vaultah/project/package/standalone.py
Importing /home/vaultah/.local/lib/python3.6/site-packages/your_package_name-0.0.0-py3.6.egg/package/__init__.py
Importing /home/vaultah/.local/lib/python3.6/site-packages/your_package_name-0.0.0-py3.6.egg/package/module.py
>>> module
<module 'package.module' from '/home/vaultah/.local/lib/python3.6/site-packages/your_package_name-0.0.0-py3.6.egg/package/module.py'>
>>> import sys
>>> sys.modules['package']
<module 'package' from '/home/vaultah/.local/lib/python3.6/site-packages/your_package_name-0.0.0-py3.6.egg/package/__init__.py'>
>>> sys.modules['package.module']
<module 'package.module' from '/home/vaultah/.local/lib/python3.6/site-packages/your_package_name-0.0.0-py3.6.egg/package/module.py'>

Note: If you decide to go down this route, you'd be better off using virtual environments to install packages in isolation.

Solution #4: Use absolute imports and some boilerplate code

Frankly, the installation is not necessary - you could add some boilerplate code to your script to make absolute imports work.

I'm going to borrow files from Solution #1 and change standalone.py:

  1. Add the parent directory of package to sys.path before attempting to import anything from package using absolute imports:

    import sys
    from pathlib import Path # if you haven't already done so
    file = Path(__file__).resolve()
    parent, root = file.parent, file.parents[1]
    sys.path.append(str(root))
    
    # Additionally remove the current file's directory from sys.path
    try:
        sys.path.remove(str(parent))
    except ValueError: # Already removed
        pass
    
  2. Replace the relative import by the absolute import:

    from package import module  # absolute import
    

standalone.py runs without problems:

vaultah@base:~$ python3 -i package/standalone.py
Running /home/vaultah/package/standalone.py
Importing /home/vaultah/package/__init__.py
Importing /home/vaultah/package/module.py
>>> module
<module 'package.module' from '/home/vaultah/package/module.py'>
>>> import sys
>>> sys.modules['package']
<module 'package' from '/home/vaultah/package/__init__.py'>
>>> sys.modules['package.module']
<module 'package.module' from '/home/vaultah/package/module.py'>

I feel that I should warn you: try not to do this, especially if your project has a complex structure.


As a side note, PEP 8 recommends the use of absolute imports, but states that in some scenarios explicit relative imports are acceptable:

Absolute imports are recommended, as they are usually more readable and tend to be better behaved (or at least give better error messages). [...] However, explicit relative imports are an acceptable alternative to absolute imports, especially when dealing with complex package layouts where using absolute imports would be unnecessarily verbose.

Discussions

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
relative import with no known parent package
[Newbie] Good evening, I’m a newbie using python I just created a project in Django and I want to save a basic record as the first and last name of an employee. I created a “seed.py” file within my “employee” application that should create a new record in the database with the ... More on forum.djangoproject.com
🌐 forum.djangoproject.com
7
0
June 9, 2021
Attempted relative import with no known parent package
When I run this demo.ipynb, I encounter the following import error. Theoretically, Python should be able to successfully import from the current directory using ..utils.easydict. Can you explain wh... More on github.com
🌐 github.com
July 15, 2024
ImportError: attempted relative import with no known parent package - PyScript - Anaconda Forum
I am using Pyscript in my html files for interactive integration testing. I figured out how to import files and additional modules, and it is working great. However, I am not able to use relative imports in my files. Is that unsupported? For example, I have this file structure: index.html |-scripts ... More on forum.anaconda.com
🌐 forum.anaconda.com
0
May 4, 2022
🌐
OneUptime
oneuptime.com › home › blog › how to fix 'importerror: attempted relative import' in python
How to Fix 'ImportError: attempted relative import' in Python
January 25, 2026 - Regular package directories use __init__.py; namespace packages can work without it. The relative import error occurs because Python does not know the package context when running a file as a script.
🌐
Built In
builtin.com › articles › importerror-attempted-relative-import-no-known-parent-package
Python ImportError: Attempted Relative Import With No Known Parent Package Solved | Built In
July 22, 2025 - Summary: The “ImportError: attempted relative import with no known parent package” occurs in Python 3 when using a relative import without a recognized parent package. It can be fixed by using absolute imports, converting the module to a ...
🌐
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
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-fix-importerror-attempted-relative-import-with-no-known-parent-package
How to Fix: ImportError: attempted relative import with no known parent package - GeeksforGeeks
July 23, 2025 - The "ImportError: attempted relative import with no known parent package" error typically arises in Python projects with multiple modules or packages. Python uses the concept of packages and modules to organize code into manageable units.
Find elsewhere
🌐
Medium
medium.com › @man9r3 › vsc-attempted-relative-import-with-no-known-parent-package-20a7266c4934
Attempted Relative Import With No Known Parent Package | by Miguel Narvaez | Medium
August 8, 2023 - Attempted Relative Import With No Known Parent Package If your folder structure is already good, I mean the `__init__.py` files are well incorporated to the module folder, you can try one of the two …
🌐
YouTube
youtube.com › watch
How to Fix ImportError: Attempted Relative Import with No Known Parent Package in Python - YouTube
Summary: Discover how to fix the 'ImportError: Attempted Relative Import with No Known Parent Package' error in Python and ensure smooth importing of modules...
Published: October 21, 2024
Views: 664
🌐
Django Forum
forum.djangoproject.com › using django
relative import with no known parent package - Using Django - Django Forum
June 9, 2021 - [Newbie] Good evening, I’m a newbie using python I just created a project in Django and I want to save a basic record as the first and last name of an employee. I created a “seed.py” file within my “employee” applicati…
🌐
GitHub
github.com › OpenGVLab › InternVideo › issues › 144
Attempted relative import with no known parent package · Issue #144 · OpenGVLab/InternVideo
July 15, 2024 - Method2: Absolute Imports: If you don't want to create a package structure, use absolute imports: from InternVideo-main.InternVideo2.multi_modality.utils.easydict import EasyDict · This assumes your my_project directory is on your Python path (either in your PYTHONPATH environment variable or in a location Python searches by default). ... @yinanhe I am still running into this issue, it keeps saying "ImportError: attempted relative import with no known parent package" even though I put blank __init__.py files in every folder.
🌐
Gideonbrimleaf
gideonbrimleaf.github.io › 2021 › 01 › 26 › relative-imports-python.html
Relative Imports in Python - Without Tearing Your Hair Out | Aiming to Misbehave
January 26, 2021 - As mentioned - Python 3.3 onwards can happily create namespaces for packages without an __init__.py file so we might think we’re all good to go. Let’s try and run our tests - for now let’s say we’re executing this whilst in the project directory (that’s going to matter real quick): python tests/drink_test.py ImportError: attempted relative import with no known parent package
🌐
Iq-inc
iq-inc.com › importerror-attempted-relative-import
ImportError: attempted relative import with no known parent package – IQ Inc
February 25, 2021 - If you are making a separate file to do helpful things, why not make it an actual package? It is actually much easier than you would think. Change up your file structure so that the functionality you want to split out is in a separate folder and includes an empty __init__.py file. Something like this: . └── src/ ├── main.py └── utils/ ├── __init__.py └── util.py · With this structure, you can actually import in many different ways.
🌐
Anaconda Forum
forum.anaconda.com › technical topics › pyscript
ImportError: attempted relative import with no known parent package - PyScript - Anaconda Forum
May 4, 2022 - I am using Pyscript in my html files for interactive integration testing. I figured out how to import files and additional modules, and it is working great. However, I am not able to use relative imports in my files. Is that unsupported? For example, I have this file structure: index.html |-scripts | - a.py | - b.py | - __init__.py The file scripts/b.py uses a relative import: # file: b.py from .a import my_function_a In my index.html, I do this: ...
🌐
Stack Exchange
gis.stackexchange.com › questions › 488352 › importerror-attempted-relative-import-with-no-known-parent-package-error-when
pyqgis - "ImportError: attempted relative import with no known parent package" error when running QGIS Plugin in PyCharm - Geographic Information Systems Stack Exchange
November 30, 2024 - Or open the parent directory of your plugin in PyCharm, not the plugin directory. This is so the working directory contains the plugin directory. And, as mentioned earlier, the plugin directory needs to contain an __init__.py so it will be treated as a package. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... 1 Update QGIS Plugin from 2 to 3 ImportError cannot import name 'QPyNullVariant' from 'qgis.PyQt.QtCore'
🌐
Jupyter Community Forum
discourse.jupyter.org › notebook
Notebook Issue - Attempted Relative Import With No Known Parent Package - Notebook - Jupyter Community Forum
January 15, 2022 - On top of that, all my .ipynb files on Github are unable to be opened because it says Invalid Notebook – The Notebook Does Not Appear to Be Valid JSON. When I try to re-install a Python3 kernel on my terminal I get another error, “attempted relative import with no known parent package”. ...
🌐
Openai
model-spec.openai.com
Redirecting...
If you are not redirected, · click here
Top answer
1 of 2
5

I know I'm late to the party, but I think I've found a solution to this problem. Hopefully this will be useful to someone else working on a large Python project.

The trick is to try one import format and fall back to the other format if the first fails.

Approach 1

db.py

try:
    # Assume we're a sub-module in a package.
    from . import models
except ImportError:
    # Apparently no higher-level package has been imported, fall back to a local import.
    import models

On the plus side, this approach is pretty simple, but doesn't scale well (module names are duplicated). Scaling can be improved by importing programmatically.

Approach 2 (not recommended)

db.py

import importlib

root = 'project.modules.core'
my_modules = ['core', 'models']
for m in my_modules
    try:
        globals()[m] = importlib.import_module(root + '.' + m)
    except ImportError:
        globals()[m] = importlib.import_module(m)

globals() is the global symbol table.

Of course, now this functionality needs to be duplicated in every module. I'm not sure that's actually an improvement over the first approach. However, you can separate this logic out into its own independent package that lives somewhere on pythonpath.

Approach 3

package_importer.py

import importlib

def import_module(global_vars, root, modules):
    for m in modules
        try:
            global_vars[m] = importlib.import_module(root + '.' + m)
        except ImportError:
            global_vars[m] = importlib.import_module(m)

db.py

import package_importer

root = 'project.modules.core'
my_modules = ['core', 'models']
package_importer.import_module(globals(), root, my_modules)
2 of 2
2

This may be a bit outdated, but maybe someone else will benefit of my answer. Since python2 und python3 have different default import behavior, you have to determine between these two python versions.

Python 2.X The default behavior for import models is to look up first the relative and then the absolute search path order. Therefore it should work.

However, in Python 3.X the default behavior for import models is to look for the model only in the absolute paths (called absolute imports). The current package core gets skipped and since the module db cannot be found anywhere else in the sys.path search path, it throws an error. To resolve this issue you have to use the import statement with dots from . import models to make clear that you are trying to import from a relative directory.

If you are interested to learn more about importing python modules, I suggest you to start your research with the following key words: module search path, python package import and relative package imports

🌐
GitHub
github.com › mapping-commons › sssom-py › issues › 209
Dev environment: "ImportError: attempted relative import with no known parent package" · Issue #209 · mapping-commons/sssom-py
February 25, 2022 - Description Due to use of relative imports, e.g. from .cli instead of absolute imports, e.g. from sssom.cli, I'm getting the error: ImportError: attempted relative import with no known parent package I've seen this problem a lot in the p...