How is this different from import math?

Question

How is this different from import math?

Answer

When we just use import math, we are only telling Python to import the math module, not necessarily all of the functions inside of it.
This is not the case when we use from math import *. Now we’re saying to go into the module and import all of the functions possible, allowing us to use them all without needing to type math.function_name().
This can feel like it’s saving you time and effort, but be careful! As you’ll see in the next exercises, it can cause headache as well. What if you import a module’s entire function set and one of them has the same name as a function you’ve defined? This can cause tricky bugs because it won’t cause an error, it will simply behave in unexpected ways because you’ll have a hard time realizing which function with the same name is being used. Therefore it’s typically safer to import the functions you need, or just to stick with using the module prefix.

21 Likes

So what will we be importing this way if functions are not imported?

2 Likes

The math module itself still contains definitions of functions etc.
So using “import math” if we wanted to use the sin() function of the math module it would be called in code using
math.sin()
If we used “from math import *” it could be called using
sin()

As described above, from {modulename} import * should generally be avoided. An example would be if you imported all the functions of the math module and then imported all the functions of the numpy module (a well known 3rd party library for mathmetical operations; particularly arrays, matrices and scientific mathematics). Some of the functions from math would then be overwritten, potentially introducing bugs.

You can avoid issues like this by importing the module and only using functions from the module name, e.g. the following prevents sin() being overwritten and generally makes it easier for anyone else reading your code to work out what function is being used-


import math
import numpy as np
math.sin()
np.sin()

For math and numpy it’s best to use one or other anyway. Stick with math unless you have a good reason not to.

2 Likes

Alright. As far as I understand, that way we are importing part of the module that we need, and avoiding bringing along the unnecessary stuff.

I think I get it. It’s like if you have a folder called “alphabet” full of documents called “a” “b” “c”, etc.
But on your computer you already have a document called “a”.

If you import “alphabet” as a folder, no problem.
But if you open the folder and import “a”, “b”, “c”…all the way to “z”, then your computer will be like "Hey, there’s already an ‘a’ here. So, it would change it to “a(2)” or something. But Python would not change it to “a(2)”, it would just have two “a” files and get all confused.

2 Likes