Import math vs from math import *, is there a difference?

I was just wondering if there is a difference between “import math” or “from math import *”, is there?

4 Likes
import math

will import the math module. Any functions that you use would have to be used as math.sqrt, math.ceil, etc.

from math import *

will import all functions from math. Any functions that you use can be used as sqrt, ceil, etc.

##Analogy

Think of math as your refrigerator.

If you import the refrigerator (import math), you will need to open the refrigerator door to take out the food and bottles, like refrigerator.food, refrigerator.bottle.

But if you import everything inside the refrigerator (from math import *), then that means you can freely use the food and bottles as they have already been taken from the refrigerator and outside it (so, no need for refrigerator.food, just use food).

13 Likes

Thanks! I love the analogy.

1 Like

I love this analogy too.

is there a reason to choose “import math” and not “from math import *”?

Generally the second option is considered a bad idea since you’ll wind up with numerous new unaffailiated names polluting your namespace which can make it difficult for anyone who has to read your code and in some cases can result in names overlapping/colliding with unintended consequences. Where possible stick with importing the module by its name or a similar alias/reference.

1 Like

loved your analogy, impressive sir