Skip to content

Commit 8f1c531

Browse files
committed
pythongh-154610: Use repr() to format the attribute name in AttributeError
* In Python code, replace `%s` with f-string `{name!r}`. * In C code, replace `'%U'` with `%R`. * In C code, no longer truncate long type names: replace `%.50s` or `%.100s` with `%s` (PEP 737).
1 parent b1e530e commit 8f1c531

15 files changed

Lines changed: 75 additions & 35 deletions

File tree

‎Lib/_pydecimal.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3953,7 +3953,7 @@ def __setattr__(self, name, value):
39533953
return object.__setattr__(self, name, value)
39543954
else:
39553955
raise AttributeError(
3956-
"'decimal.Context' object has no attribute '%s'" % name)
3956+
f"'decimal.Context' object has no attribute {name!r}")
39573957

39583958
def __delattr__(self, name):
39593959
raise AttributeError("%s cannot be deleted" % name)

‎Lib/calendar.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def __getattr__(name):
5454
else:
5555
return 2
5656

57-
raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
57+
raise AttributeError(f"module '{__name__}' has no attribute {name!r}")
5858

5959

6060
# Constants for months

‎Lib/enum.py‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -190,9 +190,8 @@ def __get__(self, instance, ownerclass=None):
190190
if self.member is not None:
191191
return self.member
192192
else:
193-
raise AttributeError(
194-
'%r has no attribute %r' % (ownerclass, self.name)
195-
)
193+
errmsg = f'{ownerclass!r} has no attribute {self.name!r}'
194+
raise AttributeError(errmsg)
196195
if self.fget is not None:
197196
# use previous enum.property
198197
return self.fget(instance)
@@ -206,9 +205,8 @@ def __get__(self, instance, ownerclass=None):
206205
try:
207206
return ownerclass._member_map_[self.name]
208207
except KeyError:
209-
raise AttributeError(
210-
'%r has no attribute %r' % (ownerclass, self.name)
211-
) from None
208+
errmsg = f'{ownerclass!r} has no attribute {self.name!r}'
209+
raise AttributeError(errmsg) from None
212210

213211
def __set__(self, instance, value):
214212
if self.fset is not None:

‎Lib/test/test_builtin.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1226,6 +1226,10 @@ def test_getattr(self):
12261226
self.assertRaises(AttributeError, getattr, sys, chr(sys.maxunicode))
12271227
# unicode surrogates are not encodable to the default encoding (utf8)
12281228
self.assertRaises(AttributeError, getattr, 1, "\uDAD1\uD51E")
1229+
with self.assertRaises(AttributeError) as cm:
1230+
getattr(object(), "a'b")
1231+
self.assertEqual(str(cm.exception),
1232+
'\'object\' object has no attribute "a\'b"')
12291233

12301234
def test_hasattr(self):
12311235
self.assertTrue(hasattr(sys, 'stdout'))
@@ -2155,6 +2159,15 @@ def test_setattr(self):
21552159
msg = r"^attribute name must be string, not 'int'$"
21562160
self.assertRaisesRegex(TypeError, msg, setattr, sys, 1, 'spam')
21572161

2162+
class A:
2163+
__slots__ = ()
2164+
2165+
with self.assertRaises(AttributeError) as cm:
2166+
setattr(object(), "a'b", 1)
2167+
self.assertEqual(str(cm.exception),
2168+
'\'object\' object has no attribute "a\'b" '
2169+
'and no __dict__ for setting new attributes')
2170+
21582171
# test_str(): see test_str.py and test_bytes.py for str() tests.
21592172

21602173
def test_sum(self):

‎Lib/test/test_decimal.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3695,6 +3695,19 @@ def test_to_integral_value(self):
36953695
self.assertRaises(TypeError, c.to_integral_value, '10')
36963696
self.assertRaises(TypeError, c.to_integral_value, 10, 'x')
36973697

3698+
def test_setattr(self):
3699+
Context = self.decimal.Context
3700+
3701+
ctx = Context()
3702+
ctx.prec = 123
3703+
with self.assertRaises(AttributeError):
3704+
ctx.xyz = 1
3705+
with self.assertRaises(AttributeError) as cm:
3706+
setattr(ctx, "a'b", 1)
3707+
self.assertEqual(str(cm.exception),
3708+
'\'decimal.Context\' object has no attribute "a\'b"')
3709+
3710+
36983711
@requires_cdecimal
36993712
class CContextAPItests(ContextAPItests, unittest.TestCase):
37003713
decimal = C

‎Lib/test/test_module/__init__.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ def test_missing_getattr(self):
4747
self.assertRaisesRegex(
4848
AttributeError, "module 'foo' has no attribute 'not_here'",
4949
getattr, foo, "not_here")
50+
self.assertRaisesRegex(
51+
AttributeError, 'module \'foo\' has no attribute "a\'b"',
52+
getattr, foo, "a'b")
5053

5154
def test_no_docstring(self):
5255
# Regularly initialized module, no docstring

‎Lib/test/test_unittest/test_case.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -796,6 +796,10 @@ def testAssertHasAttr(self):
796796
self.assertHasAttr(a, 'y')
797797
self.assertEqual(str(cm.exception),
798798
"'List' object has no attribute 'y'")
799+
with self.assertRaises(self.failureException) as cm:
800+
self.assertHasAttr(a, "a'b")
801+
self.assertEqual(str(cm.exception),
802+
'\'List\' object has no attribute "a\'b"')
799803
with self.assertRaises(self.failureException) as cm:
800804
self.assertHasAttr(List, 'spam')
801805
self.assertEqual(str(cm.exception),

‎Lib/test/test_unittest/testmock/testmock.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -685,6 +685,11 @@ def test_attributes(mock):
685685
"Mock object has no attribute 'z'",
686686
getattr, mock, 'z'
687687
)
688+
self.assertRaisesRegex(
689+
AttributeError,
690+
'Mock object has no attribute "a\'b"',
691+
getattr, mock, "a'b"
692+
)
688693
self.assertRaisesRegex(
689694
AttributeError,
690695
"Mock object has no attribute '__foobar__'",

‎Lib/unittest/mock.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -808,13 +808,13 @@ def __setattr__(self, name, value):
808808
elif (self._spec_set and self._mock_methods is not None and
809809
name not in self._mock_methods and
810810
name not in self.__dict__):
811-
raise AttributeError("Mock object has no attribute '%s'" % name)
811+
raise AttributeError(f"Mock object has no attribute {name!r}")
812812
elif name in _unsupported_magics:
813-
msg = 'Attempting to set unsupported magic method %r.' % name
813+
msg = f'Attempting to set unsupported magic method {name!r}.'
814814
raise AttributeError(msg)
815815
elif name in _all_magics:
816816
if self._mock_methods is not None and name not in self._mock_methods:
817-
raise AttributeError("Mock object has no attribute '%s'" % name)
817+
raise AttributeError(f"Mock object has no attribute {name!r}")
818818

819819
if not _is_instance_mock(value):
820820
setattr(type(self), name, _get_method(name, value))
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Format the attribute name with :func:`repr`, instead of :func:`str`, when
2+
formatting :exc:`AttributeError` error message. For example,
3+
``getattr(object(), "a'b")`` now formats the attribute error correctly.
4+
Patch by Victor Stinner.

0 commit comments

Comments
 (0)