Skip to content Skip to sidebar Skip to footer

From-import While Retaining Access By Module

The title is a little hard to understand, but my question is simple. I have a program that needs to take the sqrt() of something, but that's the only thing I need from math. It see

Solution 1:

Either way you "import" the complete math module in a sense that it's compiled and stored in sys.modules. So you don't have any optimisation benefits if you do from math import sqrt compared to import math. They do exactly the same thing. They import the whole math module, store it sys.modules and then the only difference is that the first one brings the sqrt function into your namespace and the second one brings the math module into your namespace. But the names are just references so you wont benefit memory wise or CPU wise by just importing one thing from the module.

If you want the math.sqrt syntax then just use import math. If you want the sqrt() syntax then use from math import sqrt.

If your concern is protecting the user of your module from polluting his namespace if he does a star import: from your_module import * then define a __all__ variable in your module which is a list of strings representing objects that will be imported if the user of your module does a start import.

Solution 2:

Use from math import sqrt. You can protect which functions you export from the module using an __all__ statement. __all__ should be a list of names you want to export from your module.

Solution 3:

The short answer is no. Just do from math import sqrt. It won't cause any problems if you use the script as a module, and it doesn't make the code any less readable.

Solution 4:

No, that's not possible, due to how modules work. What's wrong with import math?

Consider:

module.py

x = 1deffoo():
    return x

x = 2defbar():
    returnx

main (pseudo-code):

import main but_only foo

print foo()

Python does not know about the foo function until it hits the def foo line. What you're proposing is that a random selection of lines from the module is executed. But how can python know which lines? In this example, what value would foo() return?

Post a Comment for "From-import While Retaining Access By Module"