Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do the import statements in an imported Python module work?

Tags:

python

import

Lets say I have the following folder structure:

project/
    a.py
    module/
        b.py
        c.py
        __init__.py

a.py needs to import b.py, so it should include from module import b

b.py needs to import c.py, so it should include simply import c since they are in the same folder. But this throws a ModuleNotFoundError when a.py is run.

If I switch the line in b.py to be from module import c then a.py will run, but if I try to run b.py on its own it throws ModuleNotFoundError.

what is the correct way to import in Python?

like image 271
mannerpots Avatar asked Feb 22 '26 14:02

mannerpots


1 Answers

In python 3 try using:

from . import c

on your module/b.py file.

This forces the interpreter to look in the local folder for the module.

You wont be able to run your b module (at least not with python module/b.py), if you need it to be an executable, maybe look at:

Relative imports in Python 3

As sugested, for running your b module you can do

python -m module.b

from the parent folder.

like image 192
DSLima90 Avatar answered Feb 25 '26 05:02

DSLima90



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!