I use the math
module a lot lately. I don't want to write math.sqrt(x)
and math.sin(x)
all the time. I would like to shorten it and write sqrt(x)
and sin(x)
.
How?
For longer module names it is common to shorten them, e.g.
import numpy as np
Then you can use the short name. Or you can import the specific stuff that you need, as shown in the other anwsers:
from math import sin, sqrt
This is often used inside packages, for code that is more closely coupled. For libraries the first option with the name shortening is often the prefered way.
What you should never do is use the from math import *
form. It will pollute the name space, potentially leading to name collisions and making debugging harder. Most importantly it makes the code hard to read, because it is not clear where a particular function came from.
An exception can be made in the interactive interpreter. But once you are in the habit of using the shortened names it might not be worth to go with another convention there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With