Universal Imports


I have a question regarding the usage of "from module import function"
it says:
"Use the power of from module import * to import everything from the math module"
Wouldn’t just using

import math

do the same thing?

Edit: if we use import math, then we’d have to resort to “math.” ?


import math

We’ve just imported a namespace. Its methods and attributes must still be accessed through the parent, math.


from math import *

Now we’ve imported a collection of functions, not methods.


Test cases…

=============================== RESTART: Shell ===============================
>>> from math import *
>>> sqrt(256)
=============================== RESTART: Shell ===============================
>>> import math
>>> sqrt(256)
Traceback (most recent call last):
  File "<pyshell#147>", line 1, in <module>
NameError: name 'sqrt' is not defined
>>> math.sqrt(256)

Mind, the above (import *) uses up a tonne of resources and is not the most advisable approach. It does teach us that we can import a function from the math module.

from math import sqrt

Now the global namespace has a newly added function that is accessible from any scope in the program. And it does not take up a lot of room.

import takes a comma separated list if we wish to merge a group of methods with our namespace. That way it only takes one statement.

from math import sqrt, sin, cos

Now we can go to town on trig.


Thanks a lot! I’ve tried those three ways during the "Review: Module " lesson, and it worked without any problems.
I’ve also found out that I keep on making a lot of indentation mistakes… I’ll keep on working on them and try to get the habit of the 4 space indentation.


Be the boss where this is concerned. Before submitting a solution, clear all indents and walk the lines, inserting the applicable indentation. It’s your logic. You dictate the scopes.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.