> 
>> class Indexable[T_co::](Protocol[T_co]):
>>    def __getitem__(self, n: int) -> T_co: …
> 
> This is completely new syntax: between the class name and what it
> subclasses, you have a subscript-like syntax.
> 
> This is new semantics for subclassing, I think, unless you want
> Indexable to be a subclass of Protocol[T_co], but I'm not entirely
> sure how to read this. New semantics aren't as hard as new syntax,
> though.

[T_co::] is not super class. The subclassing semantics remain the same. It’s 
subclassing Protocol[T_co]. But instead of defining T_co outside, we define it 
inside local to the class or function. Sometimes when constructing new objects, 
we use this same brackets to help the static tools to infer the type of the 
generic. Something like the following:

T = TypeVar(“T", contravariant=True) 

@dataclass
class  A(Generic[T]):
    def method(self, x: T) -> None:
        print(f"type of x is {type(x)}") 

obj1 = A[int]() # equivalent to obj1: A[int] = A()
obj2 = A[str]() # equivalent to obj2: A[str] = A()

def str_only_func(x: str, obj: A[str]) -> None:
    obj.method(x)

str_only_func(“hi", obj1) # Not Ok 
str_only_func(“hi", obj2) # Ok 


> 
>> def get[T: int | str](n: int, object: Indexable[T]) -> T:
>>    return object[n]
> 
> Perhaps unsurprisingly, the new syntax needs to work for functions as
> well as classes. So that's not really an additional cost, it's just
> the same cost seen in another place.
> 
> What would be the semantics of this subscripting? What would be the
> meaning of, say, "def spam[42]():"? What if you leave the brackets
> empty? Cute syntax on its own doesn't make an idea; the cute syntax
> needs to be backed by a demonstration of how it's beneficial.
> 

"def spam[42]():" should throw a syntax error because 42 is not a valid 
variable name. You cannot assign to a literal. Remember between the brackets, 
we put the TypeVar, which by definition a type variable. 
Isn’t 42 = TypeVar(…) a syntax error? By extension, you can’t do ”  = 
TypeVar(…)” without specifying the variable name, meaning empty brackets should 
throw an error as well. 

Abdulla 

_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/M3U3CB2P6OR4FKWGJ2W44EWO6NWGZALP/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to