Skip to content

Commit 29e38df

Browse files
committed
Merge branch 'main' into typewatch
* main: bpo-35540 dataclasses.asdict now supports defaultdict fields (pythongh-32056) pythonGH-91052: Add C API for watching dictionaries (pythonGH-31787) bpo-38693: Use f-strings instead of str.format() within importlib (python#17058)
2 parents 415ed49 + c46a423 commit 29e38df

16 files changed

+2322
-45
lines changed

Doc/c-api/dict.rst

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,3 +238,54 @@ Dictionary Objects
238238
for key, value in seq2:
239239
if override or key not in a:
240240
a[key] = value
241+
242+
.. c:function:: int PyDict_AddWatcher(PyDict_WatchCallback callback)
243+
244+
Register *callback* as a dictionary watcher. Return a non-negative integer
245+
id which must be passed to future calls to :c:func:`PyDict_Watch`. In case
246+
of error (e.g. no more watcher IDs available), return ``-1`` and set an
247+
exception.
248+
249+
.. c:function:: int PyDict_ClearWatcher(int watcher_id)
250+
251+
Clear watcher identified by *watcher_id* previously returned from
252+
:c:func:`PyDict_AddWatcher`. Return ``0`` on success, ``-1`` on error (e.g.
253+
if the given *watcher_id* was never registered.)
254+
255+
.. c:function:: int PyDict_Watch(int watcher_id, PyObject *dict)
256+
257+
Mark dictionary *dict* as watched. The callback granted *watcher_id* by
258+
:c:func:`PyDict_AddWatcher` will be called when *dict* is modified or
259+
deallocated.
260+
261+
.. c:type:: PyDict_WatchEvent
262+
263+
Enumeration of possible dictionary watcher events: ``PyDict_EVENT_ADDED``,
264+
``PyDict_EVENT_MODIFIED``, ``PyDict_EVENT_DELETED``, ``PyDict_EVENT_CLONED``,
265+
``PyDict_EVENT_CLEARED``, or ``PyDict_EVENT_DEALLOCATED``.
266+
267+
.. c:type:: int (*PyDict_WatchCallback)(PyDict_WatchEvent event, PyObject *dict, PyObject *key, PyObject *new_value)
268+
269+
Type of a dict watcher callback function.
270+
271+
If *event* is ``PyDict_EVENT_CLEARED`` or ``PyDict_EVENT_DEALLOCATED``, both
272+
*key* and *new_value* will be ``NULL``. If *event* is ``PyDict_EVENT_ADDED``
273+
or ``PyDict_EVENT_MODIFIED``, *new_value* will be the new value for *key*.
274+
If *event* is ``PyDict_EVENT_DELETED``, *key* is being deleted from the
275+
dictionary and *new_value* will be ``NULL``.
276+
277+
``PyDict_EVENT_CLONED`` occurs when *dict* was previously empty and another
278+
dict is merged into it. To maintain efficiency of this operation, per-key
279+
``PyDict_EVENT_ADDED`` events are not issued in this case; instead a
280+
single ``PyDict_EVENT_CLONED`` is issued, and *key* will be the source
281+
dictionary.
282+
283+
The callback may inspect but must not modify *dict*; doing so could have
284+
unpredictable effects, including infinite recursion.
285+
286+
Callbacks occur before the notified modification to *dict* takes place, so
287+
the prior state of *dict* can be inspected.
288+
289+
If the callback returns with an exception set, it must return ``-1``; this
290+
exception will be printed as an unraisable exception using
291+
:c:func:`PyErr_WriteUnraisable`. Otherwise it should return ``0``.

Include/cpython/dictobject.h

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,3 +83,26 @@ typedef struct {
8383

8484
PyAPI_FUNC(PyObject *) _PyDictView_New(PyObject *, PyTypeObject *);
8585
PyAPI_FUNC(PyObject *) _PyDictView_Intersect(PyObject* self, PyObject *other);
86+
87+
/* Dictionary watchers */
88+
89+
typedef enum {
90+
PyDict_EVENT_ADDED,
91+
PyDict_EVENT_MODIFIED,
92+
PyDict_EVENT_DELETED,
93+
PyDict_EVENT_CLONED,
94+
PyDict_EVENT_CLEARED,
95+
PyDict_EVENT_DEALLOCATED,
96+
} PyDict_WatchEvent;
97+
98+
// Callback to be invoked when a watched dict is cleared, dealloced, or modified.
99+
// In clear/dealloc case, key and new_value will be NULL. Otherwise, new_value will be the
100+
// new value for key, NULL if key is being deleted.
101+
typedef int(*PyDict_WatchCallback)(PyDict_WatchEvent event, PyObject* dict, PyObject* key, PyObject* new_value);
102+
103+
// Register/unregister a dict-watcher callback
104+
PyAPI_FUNC(int) PyDict_AddWatcher(PyDict_WatchCallback callback);
105+
PyAPI_FUNC(int) PyDict_ClearWatcher(int watcher_id);
106+
107+
// Mark given dictionary as "watched" (callback will be called if it is modified)
108+
PyAPI_FUNC(int) PyDict_Watch(int watcher_id, PyObject* dict);

Include/internal/pycore_dict.h

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,32 @@ struct _dictvalues {
154154

155155
extern uint64_t _pydict_global_version;
156156

157-
#define DICT_NEXT_VERSION() (++_pydict_global_version)
157+
#define DICT_MAX_WATCHERS 8
158+
#define DICT_VERSION_INCREMENT (1 << DICT_MAX_WATCHERS)
159+
#define DICT_VERSION_MASK (DICT_VERSION_INCREMENT - 1)
160+
161+
#define DICT_NEXT_VERSION() (_pydict_global_version += DICT_VERSION_INCREMENT)
162+
163+
void
164+
_PyDict_SendEvent(int watcher_bits,
165+
PyDict_WatchEvent event,
166+
PyDictObject *mp,
167+
PyObject *key,
168+
PyObject *value);
169+
170+
static inline uint64_t
171+
_PyDict_NotifyEvent(PyDict_WatchEvent event,
172+
PyDictObject *mp,
173+
PyObject *key,
174+
PyObject *value)
175+
{
176+
int watcher_bits = mp->ma_version_tag & DICT_VERSION_MASK;
177+
if (watcher_bits) {
178+
_PyDict_SendEvent(watcher_bits, event, mp, key, value);
179+
return DICT_NEXT_VERSION() | watcher_bits;
180+
}
181+
return DICT_NEXT_VERSION();
182+
}
158183

159184
extern PyObject *_PyObject_MakeDictFromInstanceAttributes(PyObject *obj, PyDictValues *values);
160185
extern PyObject *_PyDict_FromItems(

Include/internal/pycore_interp.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,8 @@ struct _is {
144144
// Initialized to _PyEval_EvalFrameDefault().
145145
_PyFrameEvalFunction eval_frame;
146146

147+
PyDict_WatchCallback dict_watchers[DICT_MAX_WATCHERS];
148+
147149
Py_ssize_t co_extra_user_count;
148150
freefunc co_extra_freefuncs[MAX_CO_EXTRA_USERS];
149151

Lib/dataclasses.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1325,6 +1325,14 @@ def _asdict_inner(obj, dict_factory):
13251325
# generator (which is not true for namedtuples, handled
13261326
# above).
13271327
return type(obj)(_asdict_inner(v, dict_factory) for v in obj)
1328+
elif isinstance(obj, dict) and hasattr(type(obj), 'default_factory'):
1329+
# obj is a defaultdict, which has a different constructor from
1330+
# dict as it requires the default_factory as its first arg.
1331+
# https://bugs.python.org/issue35540
1332+
result = type(obj)(getattr(obj, 'default_factory'))
1333+
for k, v in obj.items():
1334+
result[_asdict_inner(k, dict_factory)] = _asdict_inner(v, dict_factory)
1335+
return result
13281336
elif isinstance(obj, dict):
13291337
return type(obj)((_asdict_inner(k, dict_factory),
13301338
_asdict_inner(v, dict_factory))

Lib/importlib/_bootstrap.py

Lines changed: 23 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ def release(self):
136136
self.wakeup.release()
137137

138138
def __repr__(self):
139-
return '_ModuleLock({!r}) at {}'.format(self.name, id(self))
139+
return f'_ModuleLock({self.name!r}) at {id(self)}'
140140

141141

142142
class _DummyModuleLock:
@@ -157,7 +157,7 @@ def release(self):
157157
self.count -= 1
158158

159159
def __repr__(self):
160-
return '_DummyModuleLock({!r}) at {}'.format(self.name, id(self))
160+
return f'_DummyModuleLock({self.name!r}) at {id(self)}'
161161

162162

163163
class _ModuleLockManager:
@@ -253,7 +253,7 @@ def _requires_builtin(fxn):
253253
"""Decorator to verify the named module is built-in."""
254254
def _requires_builtin_wrapper(self, fullname):
255255
if fullname not in sys.builtin_module_names:
256-
raise ImportError('{!r} is not a built-in module'.format(fullname),
256+
raise ImportError(f'{fullname!r} is not a built-in module',
257257
name=fullname)
258258
return fxn(self, fullname)
259259
_wrap(_requires_builtin_wrapper, fxn)
@@ -264,7 +264,7 @@ def _requires_frozen(fxn):
264264
"""Decorator to verify the named module is frozen."""
265265
def _requires_frozen_wrapper(self, fullname):
266266
if not _imp.is_frozen(fullname):
267-
raise ImportError('{!r} is not a frozen module'.format(fullname),
267+
raise ImportError(f'{fullname!r} is not a frozen module',
268268
name=fullname)
269269
return fxn(self, fullname)
270270
_wrap(_requires_frozen_wrapper, fxn)
@@ -305,11 +305,11 @@ def _module_repr(module):
305305
filename = module.__file__
306306
except AttributeError:
307307
if loader is None:
308-
return '<module {!r}>'.format(name)
308+
return f'<module {name!r}>'
309309
else:
310-
return '<module {!r} ({!r})>'.format(name, loader)
310+
return f'<module {name!r} ({loader!r})>'
311311
else:
312-
return '<module {!r} from {!r}>'.format(name, filename)
312+
return f'<module {name!r} from {filename!r}>'
313313

314314

315315
class ModuleSpec:
@@ -363,14 +363,12 @@ def __init__(self, name, loader, *, origin=None, loader_state=None,
363363
self._cached = None
364364

365365
def __repr__(self):
366-
args = ['name={!r}'.format(self.name),
367-
'loader={!r}'.format(self.loader)]
366+
args = [f'name={self.name!r}', f'loader={self.loader!r}']
368367
if self.origin is not None:
369-
args.append('origin={!r}'.format(self.origin))
368+
args.append(f'origin={self.origin!r}')
370369
if self.submodule_search_locations is not None:
371-
args.append('submodule_search_locations={}'
372-
.format(self.submodule_search_locations))
373-
return '{}({})'.format(self.__class__.__name__, ', '.join(args))
370+
args.append(f'submodule_search_locations={self.submodule_search_locations}')
371+
return f'{self.__class__.__name__}({", ".join(args)})'
374372

375373
def __eq__(self, other):
376374
smsl = self.submodule_search_locations
@@ -580,14 +578,14 @@ def _module_repr_from_spec(spec):
580578
name = '?' if spec.name is None else spec.name
581579
if spec.origin is None:
582580
if spec.loader is None:
583-
return '<module {!r}>'.format(name)
581+
return f'<module {name!r}>'
584582
else:
585-
return '<module {!r} ({!r})>'.format(name, spec.loader)
583+
return f'<module {name!r} ({spec.loader!r})>'
586584
else:
587585
if spec.has_location:
588-
return '<module {!r} from {!r}>'.format(name, spec.origin)
586+
return f'<module {name!r} from {spec.origin!r}>'
589587
else:
590-
return '<module {!r} ({})>'.format(spec.name, spec.origin)
588+
return f'<module {spec.name!r} ({spec.origin})>'
591589

592590

593591
# Used by importlib.reload() and _load_module_shim().
@@ -596,7 +594,7 @@ def _exec(spec, module):
596594
name = spec.name
597595
with _ModuleLockManager(name):
598596
if sys.modules.get(name) is not module:
599-
msg = 'module {!r} not in sys.modules'.format(name)
597+
msg = f'module {name!r} not in sys.modules'
600598
raise ImportError(msg, name=name)
601599
try:
602600
if spec.loader is None:
@@ -756,7 +754,7 @@ def find_module(cls, fullname, path=None):
756754
def create_module(spec):
757755
"""Create a built-in module"""
758756
if spec.name not in sys.builtin_module_names:
759-
raise ImportError('{!r} is not a built-in module'.format(spec.name),
757+
raise ImportError(f'{spec.name!r} is not a built-in module',
760758
name=spec.name)
761759
return _call_with_frames_removed(_imp.create_builtin, spec)
762760

@@ -1012,7 +1010,7 @@ def _resolve_name(name, package, level):
10121010
if len(bits) < level:
10131011
raise ImportError('attempted relative import beyond top-level package')
10141012
base = bits[0]
1015-
return '{}.{}'.format(base, name) if name else base
1013+
return f'{base}.{name}' if name else base
10161014

10171015

10181016
def _find_spec_legacy(finder, name, path):
@@ -1075,7 +1073,7 @@ def _find_spec(name, path, target=None):
10751073
def _sanity_check(name, package, level):
10761074
"""Verify arguments are "sane"."""
10771075
if not isinstance(name, str):
1078-
raise TypeError('module name must be str, not {}'.format(type(name)))
1076+
raise TypeError(f'module name must be str, not {type(name)}')
10791077
if level < 0:
10801078
raise ValueError('level must be >= 0')
10811079
if level > 0:
@@ -1105,13 +1103,13 @@ def _find_and_load_unlocked(name, import_):
11051103
try:
11061104
path = parent_module.__path__
11071105
except AttributeError:
1108-
msg = (_ERR_MSG + '; {!r} is not a package').format(name, parent)
1106+
msg = f'{_ERR_MSG_PREFIX} {name!r}; {parent!r} is not a package'
11091107
raise ModuleNotFoundError(msg, name=name) from None
11101108
parent_spec = parent_module.__spec__
11111109
child = name.rpartition('.')[2]
11121110
spec = _find_spec(name, path)
11131111
if spec is None:
1114-
raise ModuleNotFoundError(_ERR_MSG.format(name), name=name)
1112+
raise ModuleNotFoundError(f'{_ERR_MSG_PREFIX}{name!r}', name=name)
11151113
else:
11161114
if parent_spec:
11171115
# Temporarily add child we are currently importing to parent's
@@ -1156,8 +1154,7 @@ def _find_and_load(name, import_):
11561154
_lock_unlock_module(name)
11571155

11581156
if module is None:
1159-
message = ('import of {} halted; '
1160-
'None in sys.modules'.format(name))
1157+
message = f'import of {name} halted; None in sys.modules'
11611158
raise ModuleNotFoundError(message, name=name)
11621159

11631160
return module
@@ -1201,7 +1198,7 @@ def _handle_fromlist(module, fromlist, import_, *, recursive=False):
12011198
_handle_fromlist(module, module.__all__, import_,
12021199
recursive=True)
12031200
elif not hasattr(module, x):
1204-
from_name = '{}.{}'.format(module.__name__, x)
1201+
from_name = f'{module.__name__}.{x}'
12051202
try:
12061203
_call_with_frames_removed(import_, from_name)
12071204
except ModuleNotFoundError as exc:

0 commit comments

Comments
 (0)