[Python-projects] Variables defined in "if" statements
Mads Kiilerich
mads at kiilerich.com
Sat Feb 21 16:25:01 CET 2009
Huurne, Maarten ter wrote, On 02/20/2009 06:44 PM:
>
> 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.
>
Yes. Pylint doesn't really track conditionally defined variables. It
only checks if the defining line comes before or after it is used within
the scope, not if the definition has actually been executed. (As far as
I understand it...)
Yes, a warning for conditionally defined variables would be useful.
(However, conditionally defined variables is bad programming style
anyway (IMHO), so if a variable only is defined with a value in one
branch and not in the other (and used later outside the branch) then the
variable should be set to None before the branch. That would be how I
would remove such a warning. And that might leave the program just as
wrong as before, just without a warning ...)
Regarding checking for actual use of undefined variables ... Obviously
there are some constructs where it can't be statically decided if a
undeclared variable is used, but just as obviously it is possible to
write an "automatic" checker for any given case where it
should/shouldn't have warned about use of undeclared variables. I think
the current implementation is a fair tradeoff between correctness and
complexity/speed, but it would also be very nice with a more correct check.
I think that checking if a variable is defined is one (fundamental and
important, but still just one) property that it could be nice if pylint
could handle perfectly. In a perfect world it would also be able to
trace any other properties, assertions and invariants - where full type
inference just is a minor part ...
/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/202a1b53/attachment.bin>
More information about the Python-Projects
mailing list