Search code examples
python-importqualified-name

Qualified import in Python


I am looking for a way to import certain methods from a module in a qualified manner; for instance (pseudo-code),

from math import sqrt as math.sqrt
# ...
SQRT2 = math.sqrt(2)

Is this possible?

This is useful for managing namespaces, in order not to pollute the global namespace. Futhermore, this scheme clearly indicates the source of a method/class in any part of the code. I can also use an import math, but then the actual required methods (eg., sqrt) will be implicit.


Solution

  • You can use the built-in __import__ function with the fromlist parameter instead:

    math = __import__('math', fromlist=['sqrt'])
    SQRT2 = math.sqrt(2)