Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't import files from parent directory

Tags:

python

I can't seem to import python files from a parent directory. I ran the following commands in bash:

echo 'token="AAA111"' > config.py
mkdir scenarios
echo $'from .. import config\nprint(config.token)' > scenarios/test.py
python3 scenarios/test.py

But this gave me the error:

Traceback (most recent call last):
  File "scenarios/test.py", line 1, in <module>
    from .. import config
ValueError: attempted relative import beyond top-level package

What did I do wrong? How can I get scenarios/test.py to grab content from config.py?

like image 371
John Avatar asked Feb 02 '26 19:02

John


1 Answers

Relative imports (dots) refer to position within a package not necessarily any directory. *)

If you want to import a module from a parent directory, you would need to add it to the module search path, e.g.:

...
echo $'import config\nprint(config.token)' > scenarios/test.py
PYTHONPATH=. python3 scenarios/test.py

*) If you've had the following tree:

.
└── mypkg
    ├── __init__.py
    ├── config.py
    └── scenarios
        ├── __init__.py
        └── test.py

With from .. import config in mypkg/scenarios/test.py as in your example, then this would have worked (called from parent above mypkg/):

python3 -c 'import mypkg.scenarios.test'
like image 164
Ondrej K. Avatar answered Feb 04 '26 08:02

Ondrej K.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!