When an attribute lookup fails, Python tries to help by naming a likely candidate. The suggestion appears at the end of the error message as a "Did you mean" clause, and it has saved countless minutes spent staring at a misspelled name. Previously, it appeared only in a limited number of scenarios, while several common mistakes resulted in a generic error with no hint.
Python 3.15 extends these suggestions to three additional cases.
The first applies when the attribute does not exist on the object itself but does exist on one of its attributes:
class Inner:
def __init__(self):
self.area = 42
class Shape:
def __init__(self):
self.inner = Inner()
Shape().area
Before Python 3.15:
AttributeError: 'Shape' object has no attribute 'area'
Since Python 3.15:
AttributeError: 'Shape' object has no attribute 'area'. Did you mean '.inner.area' instead of '.area'?
Rather than reporting only that area is missing, Python looks one level deeper and reports the full path that would work. This often happens when accessing a wrapped attribute directly by mistake.
The second case covers method names adopted from other languages:
arr = [1, 2]
arr.push(3)
Before Python 3.15:
AttributeError: 'list' object has no attribute 'push'
Since Python 3.15:
AttributeError: 'list' object has no attribute 'push'. Did you mean '.append'?
The name push adds an element to an array in JavaScript, and append does the same for a list in Python. The suggestion is not based on spelling, since the two names share almost no letters. Python recognises the intent behind the name and points to its own equivalent, which is useful when switching between languages.
The third case applies to attribute deletion:
class Shape:
name = 'square'
del Shape().nam
Before Python 3.15:
AttributeError: 'Shape' object has no attribute 'nam'
Since Python 3.15:
AttributeError: 'Shape' object has no attribute 'nam'. Did you mean '.name' instead of '.nam'?
Deleting a misspelled attribute now triggers the same suggestions as accessing one. The suggestion is produced for both the del statement and the equivalent delattr call, since both go through the same lookup.
Leave a Comment
Cancel reply