[Tutor] Style question with classes and modules

Eric Brunson brunson at brunson.com
Thu Jul 19 21:57:56 CEST 2007


Tino Dai wrote:
> On 7/19/07, *Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>> 
> wrote:
>
>     > The two advantages that I can see are, I don't need to type as
>     much, and
>     > there would be a speed up in the execution of code.
>
>     Why do you expect a speedup?
>
>
> In the  Python  Reference by David Beazley on p. 40, he substituted 
> import math
> with from math import sqrt and he switched out d = d + math.sqrt(i) with
> sqrt(i). He said that that change made the program run twice as fast.  
> So therefore
> I was under the impression that "from somemodule import someclass" 
> would always be
> faster than import somemodule.

The reason it's faster is because to get the actual function for 
math.sqrt() after importing math, you have to do a dictionary lookup in 
the "math" namespace.  I don't think it should run twice as fast.  I 
would only worry about it if you had some situation where you were using 
the same name over and over:

import math
for i in range( 0, 1000000000 ):
    x = math.sqrt(i)

That's 1000000000 dictionary lookups.  Importing just the sqrt name 
would avoid those lookups, so would:

import math
f = math.sqrt
for i in range( 0, 1000000000 ):
   x = f(i)

Does that make sense?

>
>     > Is there a reason why I shouldn't?
>
>     If they belong together, put them in a package and use __init__.py. if
>     they don't belong together you are just obscuring the design for very
>     little savings.
>
>
> Ok, so I will keep the code as is. Thank you Luke and Kent!
>
> -Tino
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



More information about the Tutor mailing list