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

Huurne, Maarten ter maarten.ter.huurne at philips.com
Fri Feb 20 18:44:24 CET 2009


Hi,

When running pylint on this program:
===
def f(x):
                if x:
                                a = x
                else:
                                print a
                                print b
                                print c
                                b = x
===
The output is:
===
E0601:  6:f: Using variable 'b' before assignment
E0602:  7:f: Undefined variable 'c'
===

So pylint spots the problems with using "b" and "c", but not the problem with using "a".

I am not sure if this situation should be considered an instance of E0602, since "a" is defined, just not in this branch. So E0601 might be better, although the message is then a bit confusing: it is not defined before but it is not defined after either; it is defined some place where we decided not to go. So a third option would be to make a separate message for it.


A related situation is this code:
===
def f(x):
                if x:
                                a = x
                else:
                                b = x
                print a
                print b
===
Here pylint does not spot any problem.

While there is a message warning about possibly undefined loop variables (W0631), there does not appear to be a message for possibly undefined variables that are defined using assignment.

Also I'm not sure whether such a message should be an error or warning. If for example "x" would always evaluate to "True" and the "print b" statement would be removed, the code would execute correctly. However, there is no point in having an "if" statement if "x" is never going to evaluate to "False". Should a situation that could in theory be correct but is wrong in practice be considered an error or not?


I don't know yet if I'm going to attempt to implement checks for one or both of these situations or will open a patchless ticket for it. But I'd like to have the desired behavior clear in either case.

Bye,
                                Maarten


________________________________
The information contained in this message may be confidential and legally protected under applicable law. The message is intended solely for the addressee(s). If you are not the intended recipient, you are hereby notified that any use, forwarding, dissemination, or reproduction of this message is strictly prohibited and may be unlawful. If you are not the intended recipient, please contact the sender by return e-mail and destroy all copies of the original message.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.logilab.org/pipermail/python-projects/attachments/20090220/ae7b4a29/attachment.htm>


More information about the Python-Projects mailing list