Python relative imports


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

Suppose the structure of the program


How can I load something from the foo package from the 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 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 …


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


where attr is the filename

Scroll to Top