pythonic way to optimize access to imported value?

Bengt Richter bokr at oz.net
Thu Nov 14 04:29:21 EST 2002


On Thu, 14 Nov 2002 13:09:04 +1300, Greg Ewing <see_reply_address at something.invalid> wrote:

>Bengt Richter wrote:
>
>> Plus that version retains a reference to math, where I'd like to think that
>> I would wind up with just a reference to a double with the 3.14.. value. I.e.,
>>      def foo(pi = math.pi):
>>          return pi
>
>
>Yes, that's probably what I should have written.
>
>> Also I think I would like a keyword that governs
>> a block scope instead of just the scope of an assignment. E.g.,
>> 
>>     def foo():
>>         predef:
>>             import math
>>             pi = math.pi
>>             del math
>>             seven = 7
>>         return pi, seven
>
>
>Too complicated. You could get the same effect by putting the
>code outside the def:
>
>    from math import math_pi
did you mean
     from math import pi as math_pi
?
>
>    def foo():
>       const pi = math_pi
>       const seven = 7
>       ...
>
>    del math_pi

Not quite the same effect: you are introducing temporary global bindings.
And ISTM your version really only looks less complicated because you moved
two statements out of the local scope.

To avoid the global temp, I suppose you could write

    def foo():
        const pi = [__import__('math')][0].pi
        const seven = 7

but down that road lies much abuse, trying to cram block scope intentions
into expression scope. I don't think it's possible to anticipate what
people will want to do, except that people will tend to work around limitations
in ugly ways if there's no clean way to express their intent. So I'd rather
provide a freer "scope" ;-)

BTW, I'd suggest "preset" as closer to the semantic mark than "const" if your
proposal gets adopted. Maybe my block introducer should similarly be "presets:".
Then for minimal one-liner usage, it would look concise and similar

    def foo():
        presets: seven = 7
        ...
vs.

    def foo():
        const seven = 7
        ...

or
    def foo():
        preset seven = 7
        ...

I like the option of simple multiple values on a single line too.

    def foo():
        presets: seven = 7; eight = 2**3
        ...

Regards,
Bengt Richter



More information about the Python-list mailing list