[Python-Dev] Remove typing from the stdlib

Nick Coghlan ncoghlan at gmail.com
Mon Nov 6 23:01:23 EST 2017


On 6 November 2017 at 12:18, Nick Coghlan <ncoghlan at gmail.com> wrote:
> That particular dependency could also be avoided by defining an
> "is_class_var(annotation)" generic function and a "ClassVar" helper
> object in the dataclasses module. For example:
>
>     class _ClassVar:
>         def __init__(self, annotation):
>             self.annotation = annotation
>
>     class _MakeClassVar:
>         def __getitem__(self, key):
>             return _ClassVar(key)
>
>     ClassVar = _MakeClassVar()
>
>     @functools.singledispatch
>     def is_class_var(annotation):
>         return isinstance(annotation, _ClassVar)
>
> It would put the burden on static analysers and the typing module to
> understand that `dataclasses.ClassVar` meant the same thing
> conceptually as `typing.ClassVar`, but I think that's OK.

Eric filed a new issue for this idea here:
https://github.com/ericvsmith/dataclasses/issues/61

As I indicated in my comment there, I'm now wondering if there might
be an opportunity here whereby we could use the *dataclasses* module
to define a stable non-provisional syntactically compatible subset of
the typing module, and require folks to start explicitly depending on
the typing module (as a regular PyPI dependency) if they want anything
more sophisticated than that (Unions, Generics, TypeVars, etc).

Unlike the typing module, dataclasses *wouldn't* attempt to give
annotations any meaningful runtime semantics, they'd just be ordinary
class instances (hence no complex metaclasses required, hence a
relatively fast import time).

Beyond the API already proposed in PEP 557, this would mean adding:

* dataclasses.ClassVar (as proposed above)
* dataclasses.Any (probably just set to the literal string "dataclasses.Any")
* dataclasses.NamedTuple (as a replacement for typing.NamedTuple)
* potentially dataclasses.is_class_var (instead of dataclasses
implicitly snooping in sys.modules looking for a "typing" module)

In effect, where we now have "typing" and "typing_extensions", we'd
instead have "dataclasses" in the standard library (with the subset of
annotations needed to define data record classes), and "typing" as an
independently versioned module on PyPI.

I think such an approach could address a few problems:

- the useful-at-runtime concepts (in dataclasses) would be clearly
separated from the static-type-analysis enablers (in typing)
- type hints would still have a clear presence in the regular standard
library, but the more complex parts would be opt-in (similar to
statistics vs SciPy, secrets vs cryptography, etc)
- as various concepts in typing matured and became genuinely stable,
they could potentially "graduate" into the standard library's
dataclasses module

Cheers,
Nick.

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


More information about the Python-Dev mailing list