[New-bugs-announce] [issue45483] pure Python class that has been registered as a `collections.abc.Sequence` can't be recgnized by the match statement without the `_abc` module

GalaxySnail report at bugs.python.org
Fri Oct 15 08:59:43 EDT 2021


New submission from GalaxySnail <ylc991 at 163.com>:

Pure Python class that has been registered as a `collections.abc.Sequence` can't be recgnized by the match statement without the `_abc` module.

For example:

```
>>> from test.support.import_helper import import_fresh_module

>>> collections_abc_with_c_abc = import_fresh_module(
...     "collections.abc", fresh=["_collections_abc", "abc", "_abc"])

>>> class MyList:
...     def __init__(self, iterable):
...         self.list = list(iterable)
...     def __len__(self):
...         return len(self.list)
...     def __getitem__(self, item):
...         return self.list[item]
...
>>> collections_abc_with_c_abc.Sequence.register(MyList)
<class '__main__.MyList'>
>>> match MyList(range(3, 10)):
...     case [x, *_]:
...         print(x)
...     case _:
...         print("not a sequence")
...
3

>>> collections_abc_with_py_abc = import_fresh_module(
...     "collections.abc", fresh=["_collections_abc", "abc"], blocked=["_abc"])
>>> class MyList:
...     def __init__(self, iterable):
...         self.list = list(iterable)
...     def __len__(self):
...         return len(self.list)
...     def __getitem__(self, item):
...         return self.list[item]
...
>>> collections_abc_with_py_abc.Sequence.register(MyList)
<class '__main__.MyList'>
>>> match MyList(range(3, 10)):
...     case [x, *_]:
...         print(x)
...     case _:
...         print("not a sequence")
...
not a sequence
```

It seems to be caused by https://github.com/python/cpython/commit/069e81ab3da46c441335ca762c4333b7bd91861d , only `tp_flags` are checked in the `MATCH_SEQUENCE` opcode. `Mapping` has the same problem.

----------
messages: 404011
nosy: GalaxySnail
priority: normal
severity: normal
status: open
title: pure Python class that has been registered as a `collections.abc.Sequence` can't be recgnized by the match statement without the `_abc` module
type: behavior
versions: Python 3.10, Python 3.11

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45483>
_______________________________________


More information about the New-bugs-announce mailing list