[Python-ideas] Generics Syntax

Nick Coghlan ncoghlan at gmail.com
Thu Sep 15 07:03:21 EDT 2016


On 15 September 2016 at 19:53, Ivan Levkivskyi <levkivskyi at gmail.com> wrote:
>
>
> On 15 September 2016 at 11:46, אלעזר <elazarg at gmail.com> wrote:
>>
>> And that thread is only about variance. What about the generic syntax?
>
>
>  If you mean code like this:
>
>     class Container[+T]:
>         @abstractmethod
>         def __contains__(self, x: T) -> bool: ...
>
> then there is little chance that this will be accepted because it requires
> changes to Python syntax.

If the proposed spelling is tweaked to be "class
Container(Generic[+T]):", then it doesn't require a syntax change, as
that's merely a matter of implementing unary plus on type vars:

    >>> +object()
    Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
    TypeError: bad operand type for unary +: 'object'
    >>> class UnaryPlus:
    ...     def __pos__(self):
    ...         return self
    ...
    >>> +UnaryPlus()
    <__main__.UnaryPlus object at 0x7f5e0fe91c50>

(I have no opinion on the value of providing a simpler spelling for
covariance, I'm just noting that if you keep the "Generic[T]" aspect
of the current spelling it wouldn't require any changes to Python's
syntax and will work as far back as you care to support it)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list