Importing modules


What is the difference between the two lines below?


import math
from math import *


Technically there is no difference. The first one imports the complete math module; the second imports all the components of the math module.


There is a potential "gotcha" involved.

For sake of example, consider the function floor in math.

import math allows you to keep separate namespaces. This means that to access the function floor, we do math.floor()

if we do from math import *, then we importing all the names from math. This allows you to refer to the function simply as floor(), however if you are not careful you may cause a conflict.

Consider the following:

def floor(x):
    print int(x)

from math import *

x = 1.5

In the above example, you will not print to the console. This is because our floor function got overwritten when we imported math.

If you would like to import math.floor() as floor() in your code, you may want to explicitly import it to prevent this possible conflict.

from math import floor


Exactly the reply I was hoping to evoke. Well stated. Thank you for the correction..