[Python-ideas] add __contains__ into the "type" object

Ryan Hiebert ryan at ryanhiebert.com
Thu Mar 2 09:44:25 EST 2017


By itself, I don't see using the ``in`` syntax to check for ``instanceof`` as a big benefit, given the overhead of learning that new concept. However, given in the light of a bigger concept, I think it may make more sense.

If we accept that it may be desirable to work with types as set-like objects, apart from (in most cases) iteration, then some other shorthands become reasonable too.

Other set operators, such as::

    list <= object  # issubclass(list, object)

Plus the other obvious comparisons.

Other set operators can be used for typing::

    list | set       #  same or similar to typing.Union[list, set]
    mixin1 & mixin2  # Represents classes that inherit from mixin1 and mixin2

When we bring typing into it, it would be cool if those resultant values also were able to do instance and subclass checks. They currently raise an error, but I think it would be possible to do if this were all built into ``type``.

And, of course, if we're bringing typing to ``type``, we can replace things like ``typing.List[int]`` with ``list[int]``, and putting those directly into signatures.

I think it would be somewhat odd to bring in *some* of the set operators to types, but leave off ``__contains__`` and inequality comparisons.


This is not a proposal of all of this, just pointing out that there are further applications to this concept. At least in the case of the typing examples, I think that there are some simplifications to be had by thinking this way. Reasons against also exist, of course, but like everything it's a trade-off to consider.


I have a repo that starts some of this, though it's currently broken due to lack of love in the middle of a refactor. I haven't tried to add any typing stuff, but that seems like an obvious extension. I wouldn't expect type checkers to work with a 3rd party module like this, but it could help demonstrate the ideas.

https://github.com/ryanhiebert/typeset

If anyone is interested enough to help flesh out this proof of concept, I'd be grateful for some collaboration, or being let know of other work like it.


More information about the Python-ideas mailing list