Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Relative import

Tags:

python

import

I am developing a Python program where it manages and runs modules ( .py python files ) which can be added by users and are imported into the main program ( foo.py ) by using import function. Here's the directory structure

Foo/
    foo.py #Main script. Imports ouput.py, core.py and bar.py when needed.
    src/
        __init__.py
        output.py #Output functions required by bar.py and foo.py
        core.py
    modules/
        __init__.py
        bar.py #Needs output.py

I can import in foo.py by using

from src.output import *

But the problem I face is that when I try to import output.py from bar.py by using

from ..src.output import *

I get the error

ValueError: Attempted relative import beyond toplevel package

I am putting the files in different directories as it makes it easier for different programmers to code it separately and I definitely need a folder 'modules' or something where .py module files can be added and its functionality be used in bar.py

And please tell me if I am doing this wrong. And feel free to suggest a better way to do it.

Thank You.

like image 570
Grim Reaper Avatar asked Oct 15 '25 22:10

Grim Reaper


1 Answers

The problem is because Foo has no __init__.py, so it is not considered a package.

Each period in a relative import refers to a package. When you do

from ..src.output import *

In bar.py, the first period refers to the current package, modules. The second period refers to the package above that, Foo. Since Foo isn't actually a package, you get an error.

P.S. Wildcard imports are frowned upon. Especially when you're importing from a distantly related package like this, I'd try to refactor it into explicit imports.

like image 121
Antimony Avatar answered Oct 17 '25 12:10

Antimony



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!