4

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.

AlQuemist
  • 1,110
  • 3
  • 12
  • 22
  • What reason were you envisioning for a reader of your code to need know, at the top of the file, which methods belonging to an imported module would later be used? – Tim M. Dec 31 '20 at 19:49

2 Answers2

4

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

math = __import__('math', fromlist=['sqrt'])
SQRT2 = math.sqrt(2)
blhsing
  • 91,368
  • 6
  • 71
  • 106
2

I am not sure what problem do you see with using import math and then math.sqrt?

Do you want to name the namespace differently? Then do something like below:

import math as pymath
# ...
SQRT2 = pymath.sqrt(2)
sophros
  • 14,672
  • 11
  • 46
  • 75
  • As I mentioned in my OP, the slight problem with `import math` is that the actually-required methods (eg., `sqrt`) are absent from the `import` statement. One may add them via a comment, though. – AlQuemist Oct 18 '18 at 17:42