[Tutor] Python conundrum

Noah Hall enalicho at gmail.com
Thu Jul 7 16:30:35 CEST 2011


On Thu, Jul 7, 2011 at 3:17 PM, Lisi <lisi.reisz at gmail.com> wrote:
> Hi! :-)
>
> >From the book I am working from:
>
> <quote> A shortcut is to do your import like this:
> from ex25 import  * </quote>
>
> Is this a new and wonderful meaning of the word "shortcut"?  _Why_, _how_ is
> that a shortcut for:
>
> import ex25
>
> when it has seven *more* characters (counting the spaces)?  Or, put another
> way, twice as many words? :-/
>
> It is obviously an alternative, but I just don't get that it is a shortcut.
>
> Thanks,
> Lisi
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Consider this -
Say I had a program that used a few functions from the math module -


import math

print math.sqrt(4)
print math.pow(2,2)
print math.factorial(5)
print math.cos(30)

Because the way import works, I would have to write math (to say "take
from the namespace math") before each function from math.
Using from math import *, I can instead write -

from math import *

print sqrt(4)
print pow(2,2)
print factorial(5)
print cos(30)

This imports the functions directly into the __main__ namespace
Now, over the course of my program, this would save hundreds of
characters, as you wouldn't need to type "math" before to state which
namespace to use.

(Of course, if using only certain functions from a module such as
math, you should really use from math import sqrt, pow, factorial,
cos)
- notice

>>> import math
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'math']

>>> from math import *
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'acos',
'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil
', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp',
'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frex
p', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma',
'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radian
s', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

>>> from math import factorial, pow, sqrt, cos
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'cos',
'factorial', 'pow', 'sqrt']

HTH.


More information about the Tutor mailing list