what's wrong with "lambda x : print x/60,x%60"

Steve Holden steve at holdenweb.com
Thu Dec 8 05:05:20 EST 2005


Paul Rubin wrote:
> Steve Holden <steve at holdenweb.com> writes:
> 
>>>All joking aside, when I have names (temporary variables or scaffolding
>>>functions) that I need to initialise a module or data structure, but then
>>>outlive their usefulness, I del the name afterwards. Am I the only one? I
>>>can't say I've seen anyone else doing that, and it feels icky to me (for
>>>no reason I can put my finger on) -- what do others think?
> 
> 
> I do that too sometimes.  I think it's a Python weakness that you
> can't declare a local var like in other languages, to go out of scope
> at the end of the current block, e.g.:
> 
>   if cond:
>     my x = 7    # make a new scope for x, goes out of scope at end of if
> 
If this genuinely troubles you then you can always isolate the scope 
with a function, though of course you also no longer have the code 
inline then.

> 
>>I don't generally speaking see the point: unless the name is
>>referencing something potentially large (like the results of a
>>database query) and won't be going out of scope soon (which typically
>>happens at the end of the current method or function) I just leave it
>>to happen automatically. If it doesn't happen (because the name exists
>>at module scope) thwn what the heck.
> 
> 
> Well, that makes the code a little bit confusing.  If you say
> 
>    x = some_intermediate_result(...)
>    do_something_with (x)
> 
> do you know for sure whether x will be needed again?

Yes.

> Are you sure you
> didn't use the name x further up in the function for something that's
> still needed?
> 
Yes. Of course, otherwise I wouldn't have used it here, would I? 
Meaningful names are the biggest help in avoiding errors like this. Are 
you trying to suggest my memory's going? ;-)

> This is one of the areas where there's tension between Python the
> scripting language, that gains by saving a few keystrokes when
> throwing together a quick hack, and Python the language for developing
> long-lasting applications that have to be maintained by multiple people.
> 
> In Haskell you can even have temporary variables inside an expression:
> 
>    x = y + y*y + 3 where y=5
> 
> sets x to 33.  I believe (not absolutely sure) that the scope of y is
> limited to that expression.

Well, as warts go the inability to tightly control the scope of 
variables isn't really that terrible, is it?

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list