Another question

Donald Beaudry donb at
Tue Apr 18 15:45:51 CEST 2000

"Jeff Massung" <jmassung at> wrote,
> Donald Beaudry wrote in message <200004172120.RAA11102 at>...
> >and this one is better still (at least on my machine):
> >
> >  def do_it():
> >      from random import randint
> >      r = [0,] * 100000
> >      for i in xrange(100000):
> >         r[i] = randint(1,10)
> >  do_it()
> >
> With the "from/import" being local, does the namespace go away after the
> function is done?

No, only the local binding to it goes away.

> How fast is importing (say I called do_it() 10000 times - then how
> efficient is your function?)

A from/import, or just an import for that matter, can be slow the
first time but very fast every time thereafter.  Modules (under normal
circumstances) only get loaded once and that's what takes the time.
Regardless, if I knew I was going to be calling do_it() many times in
a performance critical application I would not put the import inside
the function.  In that case, I would write:

  import random

  def do_it(randint = random.randint):
      r = [0,] * 100000
      for i in xrange(100000):
         r[i] = randint(1,10)

In my original example I put the from/import inside the function
because I felt that it was a less obscure way to get randint into the
function's local name space (and I knew it would only get called
once).  Getting randint into the local name space is a big win for two
reasons.  First, the dictionary look-up in the random name space is
eliminated.  Second, variable references inside functions are
optimised to array references thus they are not dictionary look-ups as
they are when outside a function.

Donald Beaudry                                     Ab Initio Software Corp.
                                                   201 Spring Street
donb at                                      Lexington, MA 02421
                  ...So much code, so little time...

More information about the Python-list mailing list