Introducing Livops 2.0! Promo codeCEOgives you 8,000 so‘m on your balance.What’s new

ImportError: attempted relative import with no known parent package: how to fix it

ImportError: attempted relative import with no known parent package means Python ran the file as a script, so it has no package for an import like from .config import X to start from. Run it as a module from the project root with python -m mybot.main, or import absolutely from a start file at the root. Its sibling, attempted relative import beyond top-level package, means the dots climb above the top package, usually because Python was started inside the package folder.

By Livops team, the people who build and run LivopsUpdated

The two forms, as the log shows them (paths vary):

Traceback (most recent call last):
  File "/app/mybot/main.py", line 1, in <module>
    from .config import TOKEN
ImportError: attempted relative import with no known parent package
  File "/app/mybot/handlers/start.py", line 1, in <module>
    from ..config import TOKEN
ImportError: attempted relative import beyond top-level package

Both come from how the program was started, not from the import line itself. This page explains how Python resolves an import with dots, why running a file and running a module give it different answers, and the fix for each case, including the start command of a bot and of a FastAPI app.

What does the error mean?

An import with leading dots is relative: one dot means the current package, and each further dot one parent up[1]. from .config import TOKEN in mybot/main.py means mybot.config, and from ..config import TOKEN in mybot/handlers/start.py means the same module, one level up.

Python works these out from the package of the module that contains the import[3]. The two messages are the two ways that can fail[5]:

  • with no known parent package: the module has no package, so there is nothing for the dots to start from.
  • beyond top-level package: it has a package, but there are more dots than package levels above it.

Script or module: where the package comes from

Take a bot laid out as a package:

project/
├── requirements.txt
└── mybot/
    ├── __init__.py
    ├── __main__.py
    ├── main.py          # from .config import TOKEN
    ├── config.py
    └── handlers/
        ├── __init__.py
        └── start.py     # from ..config import TOKEN

Run as a script, python mybot/main.py, the file is executed as the __main__ module and its __name__ is "__main__"[2]. Its __spec__ is None, even if the file could have been imported as a module[1]. It belongs to no package. The tutorial draws the conclusion: since the main module has no package, a module meant to be the main module of an application must always use absolute imports[3].

Run as a module, python -m mybot.main, Python finds mybot.main with the normal import machinery and runs it as __main__[4], with __spec__ set to that module’s spec[1]. Its package is mybot, and from .config resolves. The import system docs give the same advice: use -m if you want valid module metadata in __main__[1].

(Older answers talk about __package__. It still exists, and is '' for a top-level module[2], but Python now takes the package from __spec__.parent, and falling back to __package__ is deprecated[2].)

What ends up on the import path differs too. For a script, the folder that contains the file is put first on sys.path; for -m, the current directory is[4]. So -m has to be run from the folder that contains the package.

Started from project/ Package of the started module from .config / from ..config
python mybot/main.py none no known parent package
python -m mybot.main mybot works
python -m mybot mybot (runs mybot/__main__.py) works
cd mybot && python -m handlers.start handlers .. is beyond top-level package

python -m mybot works because, given a package name, Python runs that package’s __main__ submodule[4].

Causes and fixes

1. The start command runs a file inside the package

python mybot/main.py, python src/app/run.py, or an IDE’s Run button on the current file. Each makes that file a script, with no package.

Fix A: run it as a module, from the project root. The argument is a module name: dots instead of slashes, and no .py[4].

cd project
python -m mybot.main

Fix B: give the package a __main__.py and start the package itself[4]:

# mybot/__main__.py
import asyncio
from .main import main

asyncio.run(main())
python -m mybot

Fix C: a start file at the project root, with absolute imports. A file next to mybot/ puts project/ on sys.path when it runs[4], so mybot is importable from it, and the package’s own relative imports work as usual:

# project/run.py
import asyncio
from mybot.main import main

asyncio.run(main())

Note what does not work: changing main.py to absolute imports (from mybot.config import TOKEN) and still running python mybot/main.py. Then sys.path starts with project/mybot/, the folder of the file[4], and the error becomes ModuleNotFoundError: No module named 'mybot'.

2. Too many dots, or started inside the package

beyond top-level package most often means the program was started one folder too deep. cd mybot && python -m handlers.start makes handlers the top package, and from ..config asks for its parent, which Python does not know. Start from project/ with python -m mybot.handlers.start, and the same line works.

If the start folder is right, count the dots: one for the current package, one more for each level up[1]. An import that climbs out of your top package needs to be absolute, or the code it wants belongs inside the package.

3. The server starts in another folder

python -m searches the current directory[4], so the same command works or fails depending on where it runs: a Dockerfile’s WORKDIR, a systemd unit’s working directory, or a repository where the code is in a subfolder. Start in the folder that contains the package. Started anywhere else, python -m mybot fails with a No module named error instead, which at least names the package it looked for.

4. A FastAPI app started with python

uvicorn app.main:app takes the app as <module>:<attribute>[6] and looks for the module in --app-dir, by default the current working directory[6]. main is imported as app.main, part of the package app, so from .routers import items in it works.

The same file started as python app/main.py, with uvicorn.run(app) under if __name__ == "__main__":, is a script with no package, and its relative imports fail with this error. Start it with Uvicorn and the import string, from the folder above app/:

uvicorn app.main:app --host 0.0.0.0 --port $PORT

When Uvicorn cannot find the module at all, the message is different: see Could not import module “main”.

How to confirm the fix locally

Run the exact start command from the folder the server starts in, and let the module say what it thinks its package is:

cd project
python -c "import mybot.main"     # does the package import cleanly?
python -m mybot                   # the start command itself
# temporarily, at the top of the failing file
print(__name__, __spec__ and __spec__.parent)

__main__ None means the file ran as a script, with no package; __main__ mybot means it ran with -m and its package is mybot.

On Livops

  • The start command is found for you when it can be. For a bot, Livops looks for bot.py, main.py, app.py, run.py, src/<package>/__main__.py, or a file with if __name__ == "__main__"; for a web app, for app = FastAPI() or app = Flask(__name__) in main.py, app.py or server.py, also in a package one or two folders down, or a web: line in a Procfile. Check the command it filled in under Settings → Start: if it runs a file inside your package and that file has relative imports, change it to -m.

  • Writing it yourself. The docs show a single file as .venv/bin/python main.py and a package as .venv/bin/python -m mybot. Put it in Settings → Start, or in a Procfile at the project root, worker: for a bot and web: for a site or an API:

    worker: .venv/bin/python -m mybot

    start in livops.json is applied when the project is created; after that, the start command is changed in the project’s settings.

  • When it fails. The deploy ends as start_failed, and the Logs page shows the app’s last words, the ImportError among them, often with a Tip: line under it. A web app’s previous version keeps running; a bot’s is stopped first, so the bot is down until a deploy succeeds. See The app did not start.

  • A folder of your own that is missing shows as No module named 'X' instead. Check that it is committed with its files and that .gitignore did not drop it: Python could not find a module.

The general case of a missing module is in ModuleNotFoundError: No module named, and keeping a script or bot running in Run a Python script 24/7.

Questions

Why does python -m mybot.main work when python mybot/main.py fails?

With -m, Python imports the file as the module mybot.main, so it knows its package is mybot and from .config resolves to mybot.config. Run by path, the file becomes the __main__ module with no package, and a relative import has nothing to start from.

What is the difference between no known parent package and beyond top-level package?

No known parent package means the module has no package at all, usually because it was run as a script. Beyond top-level package means it has one, but the import has more leading dots than there are package levels above it, usually because Python was started inside the package folder.

Should I use relative or absolute imports?

Either works inside a package that is imported properly. The file you start must use absolute imports if you run it as a script, because the main module has no package. Absolute imports such as from mybot.config import TOKEN read the same from every file.

Can I fix it with sys.path.append or by setting __package__?

It can make the error go away, but it hides the real problem, the way the program is started. Setting __package__ by hand is a deprecated fallback; Python uses the module spec instead. Start the program with python -m from the project root and neither is needed.

Do I need an __init__.py in the package folder?

python -m accepts namespace packages, folders without __init__.py, since Python 3.4. Adding an __init__.py is still the clearer choice: it marks the folder as a regular package.

How do I start a FastAPI app that uses relative imports?

From the folder above the package, with uvicorn app.main:app, so Uvicorn imports main as part of the package app. Running python app/main.py with uvicorn.run inside it makes main.py the __main__ module, and its relative imports fail.

What start command should a bot written as a package use on Livops?

The one Livops documents for a package: .venv/bin/python -m mybot, with your package's name. Put it in the project's Settings, under Start, or as a worker line in a Procfile.

Sources

  1. Python docs — The import system (docs.python.org). Checked .
  2. Python docs — Data model (docs.python.org). Checked .
  3. Python tutorial — Modules (docs.python.org). Checked .
  4. Python docs — Command line and environment (docs.python.org). Checked .
  5. CPython source — Lib/importlib/_bootstrap.py (github.com). Checked .
  6. Uvicorn docs — Settings (uvicorn.dev). Checked .

Put your project online today

Connect GitHub or drop a folder. No card is asked for.

Deploy your Python bot

Got a question? — @livops_uz