Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I import a package using __import__() when the package name is only known at runtime?

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')

like image 980
Anurag Uniyal Avatar asked Jun 29 '09 11:06

Anurag Uniyal


People also ask

What does __ import __ do in Python?

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).

What is __ package __?

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__ .

What is __ loader __ in Python?

__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.

What is __ all __ in Python?

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.


1 Answers

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.
like image 50
wr. Avatar answered Oct 06 '22 23:10

wr.