A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/python/typing/issues/468 below:

Make generic types non-classes. · Issue #468 · python/typing · GitHub

It is proposed to add special methods __subclass_base__ and __class_getitem__ to CPython, these will allow making generics non-classes thus simplifying them and significantly improving their performance.
@gvanrossum, the main question now is should this be a PEP?

Motivation:

There are three main points of motivation: performance of typing module, metaclass conflicts, and large amount of hacks currently used in typing.

Performance:

The typing module is one of the heaviest and slowest modules in stdlib even with all the optimizations made. Mainly this is because subscripted generics are classes. See also #432. The three main ways how the performance will be improved:

Metaclass conflicts:

All generic types are instances of GenericMeta, so if a user uses a custom metaclass, it is hard to make a corresponding class generic. This is in particular hard for library classes, that a user doesn't control. A workaround is to always mix-in GenericMeta:

class AdHocMeta(GenericMeta, LibraryMeta):
    pass

class UserClass(LibraryBase, Generic[T], metaclass=AdHocMeta):
    ...

but this is not always practical or even possible.

Hacks and bugs that will be removed by this proposal: Details of the proposal: New methods API: Changes necessary in typing module:

Key point is instead of GenericMeta metaclass, we will have GenericAlias class.

Generic will have:

GenericAlias will have:

The generic versions of collections.abc classes will be simple subclasses like this:

class Sequence(collections.abc.Sequence, Generic[T_co]):
    pass

(typeshed of course will track that Sequence[T_co] inherits from Iterable[T_co] etc.)

Transition plan: Backwards compatibility and impact on users who don't use typing:

This proposal will allow to have practically 100% backwards compatibility with current public typing API. Actually the whole idea of introducing two special methods appeared form the desire to preserve backwards compatibility while solving the above listed problems.
The only two exceptions that I see now are that currently issubclass(List[int], List) returns True, with this proposal it will raise TypeError. Also issubclass(collections.abc.Iterable, typing.Iterable) will return False, which is actually good I think, since currently we have a (virtual) inheritance cycle between them.

With my implementation, see https://github.com/ilevkivskyi/cpython/pull/2/files, I measured negligible effects (under 1%) for regular (non-generic) classes.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4