Sunday, January 17, 2021

Friendly contest: the race is on

tl; dr: Python was wrong ;-)


After one day, I've had one valid entry submitted to the contest I announced yesterday; I've also had two other submissions from the same contributor that I deemed to be invalid for the contest. The submissions shared a similar characteristics to a different degree: the information provided by Python in the exception message did not tell the whole story and, taken on its own, might have been considered to be misleading. 

One such cases which I did not considered to be valid for this contest was the error message UnboundLocalError: local variable 'x' referenced before assignment  given for code containing the following

def f():
    x = 1
    del x
    print(x)  # raises the exception

When the exception is raised, there is indeed no trace of variable "x". So while there was an assignment for such a variable before, after deletion it no longer exists. Reading this code, instead of an UnboundLocalError, the exception that should probably be raised at this point is NameError: name 'x' is not defined ; however, Friendly-traceback's role is not to second-guess Python but to explain what an exception means and, whenever possible, give more details using the information available when the exception was raised. I considered this case and another one to be beyond the scope of what Friendly-traceback could accomplish.

The entry that I deemed to be valid was based on the following code:

class F:
    __slots__ = ["a"]

f = F()
f.b = 1

The error message given by Python in this case is AttributeError: 'F' object has no attribute 'b'. While technically correct, the problem is not that this object has no such attribute but that it cannot have such an attribute. This information can be easily obtained when the exception is raised and the information provided by Friendly-traceback now includes the following:

The object f has no attribute named b. 
Note that object f uses __slots__ which prevents the creation of new 
attributes. The following are some of its known attributes: a.

Reminder: the contest is open for 8 more days.




No comments: