Skip to content

Deprecate and remove the __subclasses__ feature in future versions #131634

@qfcy

Description

@qfcy

Feature or enhancement

Proposal:

In current CPython, all classes have a largely useless __subclasses__() method. This implementation not only incurs some memory overhead but also makes executing absolutely secure codes impossible. Users can access any built-in functions and classes through object.__subclasses__(), which undermines the security of exec and eval functions. (See stack overflow)

>>> safe_scope = {"__builtins__":{}} # Disable all built-in functions
>>>
>>> attack_expr = "(1).__class__.__base__.__subclasses__()"
>>> eval(attack_expr,safe_scope)
[<class 'type'>, <class 'async_generator'>, <class 'int'>,
<class 'bytearray_iterator'>, <class 'bytearray'>,
<class 'bytes_iterator'>, <class 'bytes'>,
<class 'PyCapsule'>,<class 'classmethod'>,...] # Contains many built-in functions, insecure
>>>

However, CPython has already introduced more modern and elegant alternatives, including __subclasshook__ and __bases__. Therefore, I propose that __subclasses__ be deprecated and gradually removed in future versions.

After deprecating __subclasses__, for compatibility, the __subclasses__ method of all classes could be retained and always return [], but it would contain nothing.

>>> object.__subclasses__()
[]
>>> int.__subclasses__()
[]
>>> type.__subclasses__(type)
[]

Additionally, my own no-subclasses library (pip install no-subclasses) has already implemented this.

Has this already been discussed elsewhere?

Not yet

Links to previous discussion of this feature:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions