Python relative imports

Question:

For some time now (as the relative import was canceled) I cannot normally solve the following question:

Suppose the structure of the program

app/
    __init__.py
    foo/
        __init__.py
        handler.py

How can I load something from the foo package from the handler.py module?

The thing is that initially the name of the package foo is unknown, I load it using importlib .

So far I found such a crutch: I cut off the __name__ variable, which in handler.py is equal to 'foo.handler' , i.e. So

foo_name = __name__.rsplit('.', 1)[0]

and then I load the module I need

needle_module = importlib.import_module('.' + <имя модуля>, foo_name)

but, somehow, it's not kosher …

Answer:

I’m looking at your scheme and I see in it that your handler is in the same package, so why do they suffer when it’s enough to write the file name ??

actually saw this

mod=__import__("attr")

where attr is the filename attr.py

Scroll to Top