Files
RustPython/extra_tests/snippets/forbidden_instantiation.py
T
Rex Ledesma 4e2e0b41c6 chore: add ruff format --check (#5774)
* chore: add `ruff format --check`

* fix tests
2025-05-12 14:20:01 +09:00

64 lines
1.5 KiB
Python

from typing import Type
from types import (
GeneratorType,
CoroutineType,
AsyncGeneratorType,
BuiltinFunctionType,
BuiltinMethodType,
WrapperDescriptorType,
MethodWrapperType,
MethodDescriptorType,
ClassMethodDescriptorType,
FrameType,
GetSetDescriptorType,
MemberDescriptorType,
)
from testutils import assert_raises
def check_forbidden_instantiation(typ, reverse=False):
f = reversed if reverse else iter
with assert_raises(TypeError):
type(f(typ()))()
dict_values, dict_items = lambda: {}.values(), lambda: {}.items()
# types with custom forward iterators
iter_types = [
list,
set,
str,
bytearray,
bytes,
dict,
tuple,
lambda: range(0),
dict_items,
dict_values,
]
# types with custom backwards iterators
reviter_types = [list, dict, lambda: range(0), dict_values, dict_items]
# internal types:
internal_types = [
GeneratorType,
CoroutineType,
AsyncGeneratorType,
BuiltinFunctionType,
BuiltinMethodType, # same as MethodWrapperType
WrapperDescriptorType,
MethodWrapperType,
MethodDescriptorType,
ClassMethodDescriptorType,
FrameType,
GetSetDescriptorType, # same as MemberDescriptorType
MemberDescriptorType,
]
for typ in iter_types:
check_forbidden_instantiation(typ)
for typ in reviter_types:
check_forbidden_instantiation(typ, reverse=True)
for typ in internal_types:
with assert_raises(TypeError):
typ()