[Python-projects] Variables defined in "if" statements

Mads Kiilerich mads at kiilerich.com
Sat Feb 21 20:37:18 CET 2009


Maarten ter Huurne wrote, On 02/21/2009 07:54 PM:
> So issue a warning for the definition instead of the use of the variable? 
> That could be an option. The warning should only be issued if the variable 
> is used after the branch though:
>
> def f(x):
> 	a = x + 1
> 	if x:
> 		b = g(x)
> 		a = b if b else x
> 	return a
>
> In this example "b" is defined inside an "if" branch, but because it is not 
> used afterwards there is no problem.
>   

Yes, that's what I'm trying to say.

> In Java, the situation where a given algorithm cannot guarantee that a 
> variable is initialized before use is considered an error in the program. 
> The algorithm is stated here:
>   http://java.sun.com/docs/books/jls/third_edition/html/defAssign.html
>
> When programming in Java, it is pretty rare to come across a situation where 
> the algorithm refuses your code while the code is correct. In other words, 
> there are few false positives on this check. And for most of the false 
> positives, there exists an alternative implementation that is accepted by 
> the algorithm and is more readable.
>
> Would it be useful to try and define "definite assignment" for Python?
>   

Yes, perhaps something similar could be done for Python. But one reason 
I use Python is to avoid the restrictions and complexity of Java ;-)

The dynamic properties of Python makes it very hard to define anything - 
much harder than for Java. But common sense, good programming style and 
pylint already implicitly defines a subset of Python where dynamic 
features isn't used much. Perhaps that could be used. But it is a moving 
target, and nobody is limited to use only that subset. Perhaps another 
subset of Python could be (well)defined. Such as RPython. The only 
problem is that then it is no longer Python ;-)

So I would be pragmatic and say that if a checker finds something which 
it thinks it understands (or doesn't) and thus has something to say to 
then it should do so. It doesn't have to be that well-defined what it 
understands; any improvement in its understanding is good, and there is 
no limit to how complex it could be made.

Also, Python doesn't use nested scopes (for example with sub-scopes for 
conditional branches) like C and Java does. What we are discussing here 
would almost introduce that in order to figure out if a branch variable 
is used later outside its "defining scope". I could imagine that that 
isn't simple.

/Mads

-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3435 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://lists.logilab.org/pipermail/python-projects/attachments/20090221/1c4b5708/attachment.bin>


More information about the Python-Projects mailing list