Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Backports

Backports

A lot of additions to Python come with backports for older Pythons. Here are a few tips for using backports:

The rules for using a backport are as follows:

Conditional requirement

Add it conditionally to your requirements. This looks something like this:

[project]
dependencies = [
    "importlib_metadata>=4.6; python_version<'3.10'",
    "importlib_resources; python_version<'3.9'",
    "typing_extensions>=4.6; python_version<'3.11'",
]

Conditional usage

Always use the backport conditionally, with the following idiom:

import sys

if sys.version_info < (3, 10):
    import importlib_metadata as metadata
else:
    from importlib import metadata

Never use try/except for a backport. The idiom above has the following advantages:

Placement in a file

Placing all conditional backports in a common location is a nice practice. Here’s a suggestion: Place all imports inside src/<package>/_compat, in the standard library structure. This provides very clean, searchable imports in your codebase that look similar to the normal usage.

For example, you could have a file src/<package>/_compat/typing.py with contents like this:

from __future__ import annotations

import sys

if sys.version_info < (3, 10):
    from typing_extensions import TypeAlias
else:
    from typing import TypeAlias

if sys.version_info < (3, 11):
    from typing_extensions import Self, assert_never
else:
    from typing import Self, assert_never

__all__ = ["TypeAlias", "Self", "assert_never"]


def __dir__() -> list[str]:
    return __all__

Ruff needs to know if you are re-exporting typing/typing_extensions, so make sure you add typing-modules = ["<package>._compat.typing"] to Ruff’s config in pyproject.toml.

Typing dependencies

While it’s not usually necessary, you can avoid the typing_extensions backport at runtime by protecting the imports with typing.TYPE_CHECKING. typing_extensions is a first-party backport and very commonly required, so there’s a good chance one of your dependencies is already pulling it. But if you really, really want to keep dependencies minimal, you can do this in your typing backport re-export file.

Common backport packages