2

How do I achieve from . import x (import module x from the current package), using __import__?

Here are some attempts that failed:

>>> __import__('.', fromlist=['x'])
ValueError: Empty module name

>>> __import__('.x')
ValueError: Empty module name

How is this done using __import__?

2 Answers 2

3

The __import__ built-in's semantics are dovetailed with the bytecode that the interpreter generates from import statements, and are not especially convenient for manual use. If I understand what you are going for correctly, this does what you want:

name = 'x'
mod = getattr(__import__('', fromlist=[name], level=1), name)

In versions of Python that have importlib, you might also be able to persuade importlib.import_module to do what you want with less ugliness, but I am not sure it is possible to get "from ." semantics that way.

Sign up to request clarification or add additional context in comments.

Comments

2
__import__(__name__, fromlist=['x'])

That should get you what you need.

2 Comments

This does an absolute import of x, which is not what was asked for; also, you need to do something with the return value.
@Zack: Yes, but since the absolute import uses the dynamically set name, you get the same result. But I'm not sure it works in a submodule.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.