Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Include/internal/pycore_dict.h
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,11 @@ extern int _PyDict_Pop_KnownHash(
Py_hash_t hash,
PyObject **result);

extern int _PyDict_Pop_ExactUnicode_LockHeld(
PyDictObject *dict,
PyObject *key,
PyObject **result);

extern void _PyDict_Clear_LockHeld(PyObject *op);

#ifdef Py_GIL_DISABLED
Expand Down
34 changes: 34 additions & 0 deletions Lib/test/test_capi/test_watchers.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,40 @@ class C: pass
self.assertEqual(str(cm.unraisable.exc_value), "boom!")
self.assert_events([])

def test_type_watcher_not_called_for_failed_module_update(self):
class Meta(type):
pass

class Key:
fail = False

def __hash__(self):
return hash('__firstlineno__')

def __eq__(self, other):
if self.fail and other == '__firstlineno__':
raise ValueError('cannot clear firstlineno')
return False

key = Key()
namespace = {key: None, '__module__': 'old_module',
'__firstlineno__': 1}
with self.assertWarns(RuntimeWarning):
C = Meta('C', (), namespace)
key.fail = True

with self.watcher(kind=self.ERROR) as wid:
self.watch(wid, C)
with catch_unraisable_exception() as cm:
with self.assertRaisesRegex(ValueError,
'cannot clear firstlineno'):
C.__module__ = 'new_module'
self.assertIsNone(cm.unraisable)
key.fail = False
self.assertEqual(vars(C)['__module__'], 'old_module')
self.assertEqual(vars(C)['__firstlineno__'], 1)
self.assert_events([])

def test_two_watchers(self):
class C1: pass
class C2: pass
Expand Down
158 changes: 158 additions & 0 deletions Lib/test/test_descr.py
Original file line number Diff line number Diff line change
Expand Up @@ -3783,6 +3783,164 @@ class Some:
self.assertIsInstance(repr(Some), str) # should not crash
self.assertIsInstance(repr(Some()), str) # should not crash

def test_set_module_clears_firstlineno(self):
class Meta(type):
pass

class DelegatingMeta(type):
def __setattr__(cls, name, value):
super().__setattr__(name, value)

for metaclass in (type, Meta, DelegatingMeta):
for module in (__name__, 'new_module'):
with self.subTest(metaclass=metaclass, module=module):
class C(metaclass=metaclass):
pass

self.assertIsInstance(vars(C)['__firstlineno__'], int)
C.__module__ = module
self.assertEqual(vars(C)['__module__'], module)
self.assertNotIn('__firstlineno__', vars(C))
C.__module__ = module # Already invalidated.
self.assertNotIn('__firstlineno__', vars(C))

class Plain:
pass

with self.assertRaises(TypeError):
del Plain.__module__

class C(metaclass=Meta):
pass

lineno = vars(C)['__firstlineno__']
del C.__module__
self.assertNotIn('__module__', vars(C))
self.assertEqual(vars(C)['__firstlineno__'], lineno)

def test_set_module_respects_metaclass_descriptor(self):
calls = []

class Meta(type):
@property
def __module__(cls):
return vars(cls)['__module__']

@__module__.setter
def __module__(cls, value):
calls.append((cls, value))

class C(metaclass=Meta):
pass

lineno = vars(C)['__firstlineno__']
C.__module__ = 'new_module'
self.assertEqual(calls, [(C, 'new_module')])
self.assertEqual(vars(C)['__module__'], __name__)
self.assertEqual(vars(C)['__firstlineno__'], lineno)

def test_set_module_write_failure_preserves_firstlineno(self):
class Meta(type):
pass

class Key:
comparisons = 0
fail_after = None

def __hash__(self):
return hash('__module__')

def __eq__(self, other):
if other == '__module__':
self.comparisons += 1
if (self.fail_after is not None
and self.comparisons > self.fail_after):
raise ValueError('cannot insert module')
return False

key = Key()
with self.assertWarns(RuntimeWarning):
C = Meta('C', (), {key: None, '__firstlineno__': 1})
del C.__module__
# Allow one lookup of the missing key, then fail during insertion.
# The number of comparisons in a lookup depends on the hash seed.
key.comparisons = 0
self.assertNotIn('__module__', vars(C))
key.fail_after = key.comparisons
key.comparisons = 0
keys = list(vars(C))
with self.assertRaises(AttributeError):
C.__module__ = 'new_module'
self.assertEqual(vars(C)['__firstlineno__'], 1)
self.assertEqual(list(vars(C)), keys)

def test_set_module_clear_failure_preserves_module(self):
class Meta(type):
pass

class Key:
fail = False

def __hash__(self):
return hash('__firstlineno__')

def __eq__(self, other):
if self.fail and other == '__firstlineno__':
raise ValueError('cannot clear firstlineno')
return False

key = Key()
namespace = {key: None, '__module__': 'old_module',
'__firstlineno__': 1}
with self.assertWarns(RuntimeWarning):
C = Meta('C', (), namespace)

key.fail = True
keys = list(vars(C))
with self.assertRaisesRegex(ValueError, 'cannot clear firstlineno'):
C.__module__ = 'new_module'
key.fail = False
self.assertEqual(vars(C)['__module__'], 'old_module')
self.assertEqual(vars(C)['__firstlineno__'], 1)
self.assertEqual(list(vars(C)), keys)

def test_set_module_invalidates_cache_after_comparison(self):
class Meta(type):
pass

holder = {}
cache_reads = []

class Key:
in_comparison = False

def __hash__(self):
return hash('__module__')

def __eq__(self, other):
if (other == '__module__' and 'C' in holder
and not self.in_comparison):
self.in_comparison = True
try:
cache_reads.append(holder['C'].__module__)
finally:
self.in_comparison = False
return False

key = Key()
namespace = {key: None, '__module__': 'old_module',
'__firstlineno__': 1}
with self.assertWarns(RuntimeWarning):
C = Meta('C', (), namespace)
holder['C'] = C

C.__module__ = 'new_module'

self.assertTrue(cache_reads)
self.assertIn('old_module', cache_reads)
self.assertEqual(vars(C)['__module__'], 'new_module')
self.assertEqual(C.__module__, 'new_module')

def test_keyword_arguments(self):
# Testing keyword arguments to __init__, __call__...
def f(a): return a
Expand Down
12 changes: 12 additions & 0 deletions Lib/test/test_inspect/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -1289,6 +1289,18 @@ def test_findsource_on_class_with_out_of_bounds_lineno(self):
with self.assertRaisesRegex(OSError, "lineno is out of bounds"):
inspect.findsource(cls)

def test_getsource_after_set_module_with_custom_metaclass(self):
class Meta(type):
pass

# Keep the original line number within the bounds of inspect.py.
ns = {'__name__': __name__, 'Meta': Meta}
exec('class C(metaclass=Meta): pass', ns)
cls = ns['C']
cls.__module__ = inspect.__name__
with self.assertRaisesRegex(OSError, 'source code not available'):
inspect.getsource(cls)

def test_getsource_on_method(self):
self.assertSourceEqual(mod2.ClassWithMethod.method, 118, 119)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Assigning :attr:`~type.__module__` now clears :attr:`~type.__firstlineno__`
when a custom metaclass uses the default attribute setter to update the
class dictionary.
56 changes: 56 additions & 0 deletions Objects/dictobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -3363,6 +3363,62 @@ PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
}


/* Remove an exact str key without comparing it to non-str keys. The caller
must hold the dict lock. */
int
_PyDict_Pop_ExactUnicode_LockHeld(PyDictObject *mp, PyObject *key,
PyObject **result)
{
assert(PyDict_Check(mp));
assert(can_modify_dict(mp));
assert(PyUnicode_CheckExact(key));

Py_hash_t hash = hash_unicode_key(key);
PyDictKeysObject *dk = mp->ma_keys;
Py_ssize_t ix;
if (dk->dk_kind == DICT_KEYS_GENERAL) {
ix = do_lookup(mp, dk, key, hash, compare_generic_exact_unicode);
}
else {
ix = unicodekeys_lookup_unicode(dk, key, hash);
}
if (ix < 0) {
if (result != NULL) {
*result = NULL;
}
return 0;
}

PyObject *old_value;
if (dk->dk_kind == DICT_KEYS_SPLIT) {
old_value = mp->ma_values->values[ix];
}
else if (dk->dk_kind == DICT_KEYS_GENERAL) {
old_value = DK_ENTRIES(dk)[ix].me_value;
}
else {
old_value = DK_UNICODE_ENTRIES(dk)[ix].me_value;
}
if (old_value == NULL) {
if (result != NULL) {
*result = NULL;
}
return 0;
}

_PyDict_NotifyEvent(PyDict_EVENT_DELETED, mp, key, NULL);
delitem_common(mp, hash, ix, Py_NewRef(old_value));

if (result != NULL) {
*result = old_value;
}
else {
Py_DECREF(old_value);
}
return 1;
}


/* Internal version of dict.pop(). */
int
_PyDict_Pop_KnownHash(PyDictObject *mp, PyObject *key, Py_hash_t hash,
Expand Down
Loading
Loading