Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

relative import in python 3.9.5

My folder structure is as follows

./fff
├── __init__.py
├── fg
│   ├── __init__.py
│   └── settings
│       ├── __init__.py
│       └── settings.py
└── obng
    └── test.py

I want to import the settings.py inside fg/settings as a module into the test.py

I have added the line

from ..fg.settings import settings

But when I run it, it gives me the following error

Traceback (most recent call last): File "/mnt/d/Repos/fff/obng/test.py", line 1, in from ..fg.settings import settings ImportError: attempted relative import with no known parent package

This style of relative importing is supported as per https://docs.python.org/3/reference/import.html#package-relative-imports

What am I doing wrong here?

like image 666
Sharath Prakash Avatar asked Aug 31 '25 04:08

Sharath Prakash


1 Answers

It is a matter of how you run your project - you should run from the parent directory of the top-level package as in

$ cd ../fff
$ python -m fff.obng.test # note no py

Then relative imports will be resolved correctly. It is an antipattern running a script directly from its folder

like image 135
Mr_and_Mrs_D Avatar answered Sep 03 '25 04:09

Mr_and_Mrs_D