Skip to content

Unpickling child class fails if base class __init_subclass__ expects an argument #527

@Gollum999

Description

@Gollum999

If you have a base class that defines __init_subclass__ with an argument, unpickling a child class will fail because cloudpickle does not pass along the original kwarg when re-creating the class.

This case seems to work fine in the built-in pickle package.

This usage mirrors examples shown in the docs and the original PEP that introduced the __init_subclass__ method.

Python 3.11.4
cloudpickle 2.2.1
EDIT: This also appears to be broken with cloudpickle 3.0.0.

Example:

#!/usr/bin/env python3
import pickle
import cloudpickle
print(cloudpickle.__version__)


class Base:
    def __init_subclass__(cls, /, arg, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.arg = arg


class Child(Base, arg='hello'):
    pass


print(pickle.loads(pickle.dumps(Base)))
print(pickle.loads(pickle.dumps(Child)))
print(cloudpickle.loads(cloudpickle.dumps(Base)))
print(cloudpickle.loads(cloudpickle.dumps(Child)))
2.2.1
<class '__main__.Base'>
<class '__main__.Child'>
<class '__main__.Base'>
Traceback (most recent call last):
  File "/home/tsanders/test_cloudpickle_bug.py", line 20, in <module>
    print(cloudpickle.loads(cloudpickle.dumps(Child)))
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/conda/envs/production-3.11/lib/python3.11/site-packages/cloudpickle/cloudpickle.py", line 827, in _make_skeleton_class
    skeleton_class = types.new_class(
                     ^^^^^^^^^^^^^^^^
  File "/opt/conda/envs/production-3.11/lib/python3.11/types.py", line 75, in new_class
    return meta(name, resolved_bases, ns, **kwds)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Base.__init_subclass__() missing 1 required positional argument: 'arg'

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions