-
-
Notifications
You must be signed in to change notification settings - Fork 33.1k
Description
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