Skip to main content

PEP 585 + PEP 604 backports.

Project description

modern_types Package version Supported Python versions

Tests Coverage Poetry Ruff Code style License Pre-commit

__modern_types__ aims to provide PEP 585 + PEP 604 backward compatibility for Python <=3.10 deferred type evaluation. Hence, the targeted Python versions are 3.8 and 3.9.

[!Note] The current version of __modern_types__ does not support variadic generics (typing_extensions.TypeVarTuple). They are to come in 2.0.0.

What does it do?

Prevents type errors in evaluating PEP 585 and PEP 604 type annotations for Python 3.8 and 3.9, which might happen in pydantic models for example.

In Python 3.8, the following code

from __future__ import annotations
from collections import defaultdict
from pprint import pprint
from typing import get_type_hints

import __modern_types__

class Foo:
    a: dict[str, int]
    b: list[int]
    c: set[int]
    d: tuple[int, ...] | None
    e: frozenset[int]
    f: defaultdict[str, int]

pprint(get_type_hints(Foo, globals(), locals()))

gives:

{"a": typing.Dict[str, int],
 "b": typing.List[int],
 "c": typing.Set[int],
 "d": typing.Union[typing.Tuple[int, ...], None],
 "e": typing.FrozenSet[int],
 "f": typing.DefaultDict[str, int]}

Use case

Keep your codebase up-to-date by speeding up migrating to modern types, even if you support Python versions >=3.8. Stop using deprecated typing.Dict, typing.List, typing.Set, typing.Tuple, typing.FrozenSet and typing.DefaultDict! Importing __modern_types__ will make all typing.get_type_hints-dependent parts of your application, including pydantic models, work with PEP 585 and PEP 604.

How to use?

Simply import __modern_types__ in your code, and it will override the default global namespace of typing.get_type_hints.

And now you can use modern types everywhere in your code and the following replacements will be applied without overwriting your parameters:

Old type New type Without __modern_types__, works on Python version... With __modern_types__, works on Python version... Backports PEP
dict[KT, VT] typing.Dict[str, int] >=3.9 >=3.8 PEP 585
list[VT] typing.List[int] >=3.9 >=3.8 PEP 585
set[int] typing.Set[int] >=3.9 >=3.8 PEP 585
tuple[int, ...] typing.Tuple[int, ...] >=3.9 >=3.8 PEP 585
frozenset[int] typing.FrozenSet[int] >=3.9 >=3.8 PEP 585
collections.defaultdict[int] typing.DefaultDict[int] >=3.9 >=3.8 PEP 585
X | Y typing.Union[X, Y] >=3.10 >=3.8 PEP 604

[!Note] Some optional replacements will also be performed if possible, according to those listed in the __modern_types__._auto source code.

__modern_types__ additionally makes sure that generic aliases above are instantiable, which isn't the default behavior.

ProTip: How to subclass built-in generic classes in Python 3.8?

Supposing you are subclassing dict, you could write either

from __future__ import annotations

from typing import Dict, Generic

KT = TypeVar("KT")
VT = TypeVar("VT")


class YourDictSubclass(Dict[KT, VT], Generic[KT, VT]):
    pass

or

from __future__ import annotations

from functools import partial
from typing import TypeVar, _GenericAlias  # type: ignore[attr-defined]

KT = TypeVar("KT")
VT = TypeVar("VT")


@partial(_GenericAlias, params=(KT, VT))
class YourDictSubclass(dict):
    pass

so that YourDictSubclass[str, int], for instance, could be used as an evaluable type annotation.

If you want an API that simplifies this, please submit an issue so it has a reason to become a feature.

Can __modern_types__ be used in production?

Yes. It shouldn't break most of the existing codebases, despite the monkeypatching.

The library simply overrides the default global namespace of typing.get_type_hints and tries to re-assign name-to-object references of un-[]-able and un-|-able types in relevant modules to valid generic aliases from the typing module, such as typing.Dict[KT, VT].

If some keys that __modern_types__ would supply to typing.get_type_hints global namespace are present, they are used instead of the __modern_types__ ones.

Installation

If you want to…

…use this tool in your project 💻

You might simply install it with pip:

pip install modern-types

If you use Poetry, then run:

poetry add modern-types

…contribute to modern_types 🚀

[!Note] If you use Windows, it is highly recommended to complete the installation in the way presented below through WSL2.

  1. Fork the modern_types repository on GitHub.

  2. Install Poetry.
    Poetry is an amazing tool for managing dependencies & virtual environments, building packages and publishing them. You might use pipx to install it globally (recommended):

    pipx install poetry
    

    If you encounter any problems, refer to the official documentation for the most up-to-date installation instructions.

    Be sure to have Python 3.8 installed—if you use pyenv, simply run:

    pyenv install 3.8
    
  3. Clone your fork locally and install dependencies.

    git clone https://github.com/your-username/modern_types path/to/modern_types
    cd path/to/modern_types
    poetry env use $(cat .python-version)
    poetry install
    

    Next up, simply activate the virtual environment and install pre-commit hooks:

    poetry shell
    pre-commit install --hook-type pre-commit --hook-type pre-push
    

For more information on how to contribute, check out CONTRIBUTING.md.
Always happy to accept contributions! ❤️

Legal info

© Copyright by Bartosz Sławecki (@bswck).
This software is licensed under the terms of MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

modern_types-1.0.4.tar.gz (15.0 kB view details)

Uploaded Source

Built Distribution

modern_types-1.0.4-py3-none-any.whl (12.2 kB view details)

Uploaded Python 3

File details

Details for the file modern_types-1.0.4.tar.gz.

File metadata

  • Download URL: modern_types-1.0.4.tar.gz
  • Upload date:
  • Size: 15.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/4.0.2 CPython/3.11.7

File hashes

Hashes for modern_types-1.0.4.tar.gz
Algorithm Hash digest
SHA256 3dcb6dcb1a034f549a39a18bfa809927d4faf80cb5903f06e72dba423c8c3979
MD5 7b22e3448dcc9191303df4fcca8c472c
BLAKE2b-256 bf3c23585a2b05d24f4fab27fb0a15a47497505e18443a384664974e2e994519

See more details on using hashes here.

File details

Details for the file modern_types-1.0.4-py3-none-any.whl.

File metadata

  • Download URL: modern_types-1.0.4-py3-none-any.whl
  • Upload date:
  • Size: 12.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/4.0.2 CPython/3.11.7

File hashes

Hashes for modern_types-1.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 6264b46346c15a0744053cd5d9fab99c6520005560f99163e59e4338bbb0b1e6
MD5 30d4b2636597d9803763ceb585875a87
BLAKE2b-256 1dab632aee29fdbe68869122846c0273577928ca0c435eaf299b87d5469cc8a9

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page