On Fri, Jul 10, 2020 at 9:54 AM Michael Lee <michael.lee.0...@gmail.com>
wrote:

> One small question about this part of the PEP:
>
> > For the most commonly-matched built-in types (bool, bytearray, bytes,
> dict, float, frozenset, int, list, set, str, and tuple), a single
> positional sub-pattern is allowed to be passed to the call. Rather than
> being matched against any particular attribute on the subject, it is
> instead matched against the subject itself.
>
> Correct me if I'm wrong, but I don't think the PEP currently gives us a
> way of enabling this behavior for classes not on this list. If so, would it
> be worth adding a way?
>
> It would help remove a special case and could come in handy when doing
> things like creating my own custom data structures, for example. After all,
> if `case dict(x)` makes x match the entire dict, it would be nice if I
> could make `case MyCustomMapping(x)` behave in the same way to keep the
> usage consistent.
>
> We could maybe let classes opt-in to this behavior if they define 
> `__match_args__
> = None`? Not sure if adding the extra "is None" check when doing the
> match will introduce too much overhead though.
>
> -- Michael
>

Hi MIchael,

There is a way to do this. A class could do this:
```
class C:
    __match_args__ = ["__self__"]

    @property
    def __self__(self):
        return self
```
(You can use any name for `__self__`.)

I realize this isn't particularly pretty, but we feel it's better not to
add a custom `__match__` protocol at this time: The design space for that
is itself quite large, and we realized that almost all "easy" applications
could be had without it, while the "complicated" applications were all
trying to get the `__match__` protocol to do different things.

Also, beware that if your class does this, it is stuck with this form -- if
you replace `["__self__"]` with some other set of arguments, user code that
is matching against your class will presumably break.

-- 
--Guido van Rossum (python.org/~guido)
*Pronouns: he/him **(why is my pronoun here?)*
<http://feministing.com/2015/02/03/how-using-they-as-a-singular-pronoun-can-change-the-world/>
_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-le...@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at 
https://mail.python.org/archives/list/python-dev@python.org/message/NY3RKJTD6SW7K4XQC4DDUZKJTHZKNBZW/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to