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

Matt Joiner
  • 112,946
  • 110
  • 377
  • 526

2 Answers2

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.

zwol
  • 135,547
  • 38
  • 252
  • 361
2
__import__(__name__, fromlist=['x'])

That should get you what you need.

  • This does an *absolute* import of `x`, which is not what was asked for; also, you need to do something with the return value. – zwol Dec 07 '11 at 00:33
  • @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. – Lennart Regebro Dec 07 '11 at 22:47