Pregunta

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 seems a bit wasteful to import the entire module to grab a single function.

I could say from math import sqrt, but then sqrt() would be added to my program's main namespace and I don't want that (especially since I plan to alter the program to be usable as a module; would importing like that cause problems in that situation?). Is there any way to import only that one function while still retaining the math.sqrt() syntax?

I'm using Python 2.7 in this specific case, but if there's a different answer for Python 3 I'd like to hear that too for future reference.

¿Fue útil?

Solución

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.

Otros consejos

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.

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.

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

Consider:

module.py

x = 1

def foo():
    return x

x = 2

def bar():
    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?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top