MCPcopy Create free account
hub / github.com/cloudpipe/cloudpickle / reducer_override

Method reducer_override

cloudpickle/cloudpickle.py:1369–1413  ·  view source on GitHub ↗

Type-agnostic reducing callback for function and classes. For performance reasons, subclasses of the C `pickle.Pickler` class cannot register custom reducers for functions and classes in the dispatch_table attribute. Reducers for such types must instead

(self, obj)

Source from the content-addressed store, hash-verified

1367 # not be the case anymore when pypy implements protocol 5.
1368
1369 def reducer_override(self, obj):
1370 """Type-agnostic reducing callback for function and classes.
1371
1372 For performance reasons, subclasses of the C `pickle.Pickler` class
1373 cannot register custom reducers for functions and classes in the
1374 dispatch_table attribute. Reducers for such types must instead
1375 implemented via the special `reducer_override` method.
1376
1377 Note that this method will be called for any object except a few
1378 builtin-types (int, lists, dicts etc.), which differs from reducers
1379 in the Pickler's dispatch_table, each of them being invoked for
1380 objects of a specific type only.
1381
1382 This property comes in handy for classes: although most classes are
1383 instances of the ``type`` metaclass, some of them can be instances
1384 of other custom metaclasses (such as enum.EnumMeta for example). In
1385 particular, the metaclass will likely not be known in advance, and
1386 thus cannot be special-cased using an entry in the dispatch_table.
1387 reducer_override, among other things, allows us to register a
1388 reducer that will be called for any class, independently of its
1389 type.
1390
1391 Notes:
1392
1393 * reducer_override has the priority over dispatch_table-registered
1394 reducers.
1395 * reducer_override can be used to fix other limitations of
1396 cloudpickle for other types that suffered from type-specific
1397 reducers, such as Exceptions. See
1398 https://github.com/cloudpipe/cloudpickle/issues/248
1399 """
1400 t = type(obj)
1401 try:
1402 is_anyclass = issubclass(t, type)
1403 except TypeError: # t is not a class (old Boost; see SF #502085)
1404 is_anyclass = False
1405
1406 if is_anyclass:
1407 return _class_reduce(obj)
1408 elif isinstance(obj, types.FunctionType):
1409 return self._function_reduce(obj)
1410 else:
1411 # fallback to save_global, including the Pickler's
1412 # dispatch_table
1413 return NotImplemented
1414
1415 else:
1416 # When reducer_override is not available, hack the pure-Python

Callers

nothing calls this directly

Calls 2

_function_reduceMethod · 0.95
_class_reduceFunction · 0.85

Tested by

no test coverage detected