I have a messages folder(package) with __init__.py
file and another module messages_en.py
inside it. In __init__.py
if I import messages_en
it works, but __import__
fails with "ImportError: No module named messages_en"
import messages_en # it works
messages = __import__('messages_en') # it doesn't ?
I used to think 'import x' is just another way of saying __import__('x')
One can use the Python's inbuilt __import__() function. It helps to import modules in runtime also. level : Specifies whether to use absolute or relative imports. Default is -1(absolute and relative).
That is, if a module is in a package, __package__ is set to the package name to enable explicit relative imports. Specifically: When the module is a package, its __package__ value should be set to its __name__ .
__loader__ is an attribute that is set on an imported module by its loader. Accessing it should return the loader object itself. In Python versions before 3.3, __loader__ was not set by the built-in import machinery. Instead, this attribute was only available on modules that were imported using a custom loader.
In the __init__.py file of a package __all__ is a list of strings with the names of public modules or other objects. Those features are available to wildcard imports. As with modules, __all__ customizes the * when wildcard-importing from the package.
If it is a path problem, you should use the level
argument (from docs):
__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module
Level is used to determine whether to perform
absolute or relative imports. -1 is the original strategy of attempting
both absolute and relative imports, 0 is absolute, a positive number
is the number of parent directories to search relative to the current module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With