pythonic way to optimize access to imported value?

Greg Ewing see_reply_address at something.invalid
Tue Nov 12 20:32:02 EST 2002


Bengt Richter wrote:

>  >>> def mkfoo():
>  ...     from math import pi
>  ...     def foo():
>  ...         return pi
>  ...     return foo
>  ...
> 
> What would be best Pythonic practice for getting a foo2? It seems like if there were
> a way to say "do this part once at compile time"


It's not really compile-time that we want to do it,
but module load time, or perhaps function definition
time.

One way would be to use a default-argument hack:

    import math

    def foo(m = math):
       return m.pi

but this has all the usual drawbacks of the default-argument
hack.

This suggests that perhaps there should be a way
of getting something that is just like a default
argument, except that it's not part of the argument
list. Maybe

    def foo():
       const m = math
       return m.pi

The "const" statement would be evaluated when
the "def" was executed, and "m" would appear in the
local namespace when the function was called.

Although "const" might not be the best name for
it, since it's not really a constant, more like
a local with an initial value.

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg




More information about the Python-list mailing list