Proposal: local variable declarations and type advice

Paul Rubin phr-n2002a at nightsong.com
Tue Feb 26 02:06:10 EST 2002


Courageous <jkraska at san.rr.com> writes:
> The list part of me wants:
> 
> 	x = 3
> 	let ( x ):
> 		x = 5
> 
> I might call it something other than "let" to make it Pythonic, though.

That's got its attractions, but doesn't handle loop indices so well.

> >2) Add a compiler option similar to Perl's "use strict",
> 
> This has been brought up before. Personally, I favor the idea of a
> directive of some kind, on per module basis, that affects that
> module for that module's data. One of the reasons you're not seeing
> too many people clamour for this kind of thing, however, is that
> misspellings are (so it is claimed, and so my own personal
> experience suggests) actually a relatively scarce cause of Python
> problems.

Besides misspellings, there's a class of bugs where you patch a program
by inserting some code in the middle, not noticing you've clobbered
a variable from far away in the function.  Local scope prevents that.
Use strict makes sure you don't omit a local declaration by accident.

> You can get some of this kind of behavior _now_ by the way. Just implement
> a class which doesn't allow setattr to work on an instance for any variable
> which doesn't likewise exist in it class.

I'm talking about ordinary variables in functions, not class instance
variables.

> *Poof, Guido uses his time machine*
> 
> >   Example 2:
> >     local x(int)
> >     x = "banana"    # implementation-dependent behavior
> 
> I disagree here. If you've gone to the trouble of declaring something,
> to get full use, you need a defined error; further, it would be helfpul
> if this occured prior to execution.

The implementation can define an appropriate error.  I don't mean the
implementation is supposed to go off and do something totally unpredictable.

Also, that particular example is easy for the compiler to flag by
static analysis; but there's also cases like

  x = frob(3)

where frob turns out to return a string if the arg happens to be 3?
In general, the compiler can't figure that out.

> There's some good cause for resistance to this. One of those things which
> keeps Python Pythonic is it's concise expressivity. Declarations foil that.

The declarations are no less concise than assert statements (for error
checking).  For compiler advice, they're like pragmas.



More information about the Python-list mailing list