pylint #5719 E0601 false negative (variable referenced before assignment) [resolved]

Maarten wrote :

In the following Python fragment, the variable "x" is referenced before it is assigned in two occasions:

def f(n):
  if n == 0:
      if x == 1:
      print x
      x = 3

There is a rule in the "variables" checker that should catch errors like this: message E0601. But for some reason this message is not issued.

The reason seems to be the "if x == 1" statement. If this is replaced by "pass", the message will be issued.

I looked at the code of the variables checker and the implementation of E0601 is in the visit_name() method. This is the final part of the decision whether to issue the message or not:

if (maybee0601
    and stmt.source_line() <= defstmt.source_line()
    and not is_defined_before(node)
    and not are_exclusive(stmt, defstmt)):
    self.add_message('E0601', args=name, node=node)

I added some debug prints and the reason the message is not issued is that "are_exclusive(stmt, defstmt)" returns True. Here "stmt" is the "if x == 1" statement and "defstmt" is the "x = 3" assignment. Indeed those two branches are exclusive. However, that is not a valid reason why the use of "x" should be considered correct. In fact, when the branch in which a variable is assigned is exclusive to a branch in which a variable is used, that would be a reason to consider its use wrong.

I hope someone who is more familiar with the pylint code can figure out what the proper role of are_exclusive() should be for triggering E0601.

appeared in<not specified>
done in0.18.0
load left0.000
closed by<not specified>