CarliJoy / intersection_examples

Python Typing Intersection examples
MIT License
33 stars 2 forks source link

Support variable intersections #21

Closed NeilGirdhar closed 1 year ago

NeilGirdhar commented 1 year ago

I just want to mention one more example here, which requires Union and Intersection, which is when the number of things intersected is variable. This can happen when TypeVarTuple are involved, and it kind of implies that a speccing of empty unions and empty intersections is necessary. (See https://github.com/python/typing/issues/1362)

from typing import TypeVarTuple, Union

items = TypeVarTuple("items")
protocols = TypeVarTuple("protocols")   # something like tuple[type[Protocol], ...]

def pick_random_element(tup: tuple[*items]) -> Union[*items]: ...
    """Return random element form a tuple."""
    # if tuple is empty, raises an exception ⟺ return `Never`.

def create_intersection_protocol(tuple: tuple[*protocols]) -> type[Intersection[*Protocols]]: ...
    """Creates the intersection of pairwise disjoint protocol classes."""
    # if intersection is empty, returns a protocol that matches with any class.

EMPTY_TUPLE = ()
pick_random_element(EMPTY_TUPLE)  # should reveal as `Never`.
create_intersection_protocol(EMPTY_TUPLE)  # should reveal as `object`!?

Note that bounds are (not yet) supperted by TypeVarTuple, so the latter cannot be hinted properly right now.

_Originally posted by @randolf-scholz in https://github.com/CarliJoy/intersection_examples/issues/12#issuecomment-1665869505_

NeilGirdhar commented 1 year ago

(My mistake in creating this issue.)