Skip to main content

typenames : String representations of type annotations

Docs Status PyPI conda-forge Supported Python versions tests coverage mypy pyrefly ty

typenames is a configurable Python library for creating string representations of type annotations. By default, it produces compact representations by removing standard library module names. Configurable options include standardizing on | operator syntax for unions or standard collections classes for generics.

import typing
from typenames import typenames

typenames(int)
#> 'int'
typenames(dict[str, typing.Any])
#> 'dict[str, Any]'
typenames(str | int)
#> 'str | int'
typenames(typing.Optional[str])
#> 'Optional[str]'

Why use this library?

String representations of Python type objects, type aliases, and special typing forms are inconsistent and often verbose. Here are some comparisons using default settings against built-in string representations:

Input With str(...) With typenames(...)
int <class 'int'> int
list <class 'list'> list
typing.Optional[int] typing.Optional[int] Optional[int]
collections.abc.Iterator[typing.Any] collections.abc.Iterator[typing.Any] Iterator[Any]
typing.Literal[MyEnum.NAME] typing.Literal[<MyEnum.NAME: 'value'>] Literal[MyEnum.NAME]

typenames also has handy configurable functionality, such as:

  • Forcing standardization on | operator union syntax (e.g., Union[int, str] to int | str) or vice versa
  • Forcing standardization on | operator optional syntax (e.g., Optional[int] to int | None) or vice versa
  • Forcing standardization on standard collection types for generics (e.g., List[int] to list[int]) or vice versa
  • Controlling exactly which module names to remove using regex patterns.

No need for string manipulation to get what you want!

Installation

typenames is available on PyPI:

pip install typenames

It is also available on conda-forge:

conda install typenames --channel conda-forge

Basic Usage

The main way to use the library is the typenames function. Calling it on a type annotation renders a string representation:

import collections.abc
import typing
from typenames import typenames

typenames(int)
#> 'int'
typenames(typing.Optional[str])
#> 'Optional[str]'
typenames(collections.abc.Callable[[int], tuple[str, ...]])
#> 'Callable[[int], tuple[str, ...]]

Under the hood, typenames parses a type annotation as a tree structure. If you need to see the parsed tree, use the parse_type_tree function to return the root node. You can get the rendered string representation by calling str(...) on root node.

import typing
from typenames import parse_type_tree

tree = parse_type_tree(typing.Union[typing.Any, list[typing.Any]])
tree
#> <GenericNode typing.Union[<TypeNode typing.Any>, <GenericNode <class 'list'>[<TypeNode typing.Any>]>]>
str(tree)
#> 'Union[Any, list[Any]]'

Configurable options

All configuration options can be passed as keyword arguments to either the typenames or parse_type_tree functions.

Union Syntax (union_syntax)

This option controls how unions are rendered. It supports both the typing.Union special form and the | operator (bitwise or) syntax from PEP 604. Valid options are defined by the enum UnionSyntax and include:

  • "as_given" (default): render the union as it is given without changing syntax.
  • "or_operator": render all type unions using the | operator.
  • "special_form": render all type unions using the typing.Union special form.

Optional Syntax (optional_syntax)

This option controls how optional types are rendered. It supports both the typing.Optional special form and the | operator (bitwise or) syntax from PEP 604. Valid options are defined by the enum OptionalSyntax and include:

  • "as_given" (default): render the optional type as it is given without changing syntax
  • "or_operator": render all optional types using the | operator
  • "union_special_form": render all optional types using the typing.Optional special form
  • "optional_special_form": render all optional types using the typing.Optional special form

Standard Collection Syntax (standard_collection_syntax)

Default value changed in v2.0.0

This option controls how parameterized standard collection generic types are rendered. It supports both the typing module's generic aliases (e.g., typing.List[...]) and the standard class (e.g., list[...]) syntax from PEP 585. Valid options are defined by the enum StandardCollectionSyntax and include:

  • "standard_class" (default): render all parameterized standard collection generic types using their class
  • "as_given": render the parameterized generic type as it is given without changing syntax
  • "typing_module": render all parameterized standard collection generic types using the typing module's generic alias

Removing Module Names (remove_modules)

This option controls how module names are removed from the rendered output. It takes a list of inputs, which can either be a string of the module name or a re.Pattern regex pattern directly (the result of re.compile). String inputs are templated into the following regex pattern:

module: str  # Given module name
re.compile(r"^{}\.".format(module.replace(".", r"\.")))

Note that module names are removed in the given order, so having entries that are submodules of other entries can potentially lead to the wrong behavior. You can either order them from higher-depth to lower-depth, or directly provide a compiled pattern with optional groups. For example, the pattern re.compile(r"^collections\.(abc\.)?") will match both "collections." and "collections.abc.".

The default list of module names include the standard library modules relevant to PEP 585 plus types and typing. It can be accessed at DEFAULT_REMOVE_MODULES.

DEFAULT_REMOVE_MODULES: List[Union[str, re.Pattern]] = [
    "__main__",
    "builtins",
    re.compile(r"^collections\.(abc\.)?"),
    "contextlib",
    "re",
    "types",
    "typing",
]

If you are trying to add additional modules to this option (rather than overriding the defaults), the easiest way to do so is to concatenate with the default list:

from typing import Optional
from typenames import typenames, DEFAULT_REMOVE_MODULES, BaseNode

# Default removals
typenames(Optional[BaseNode])
#> 'Optional[typenames.BaseNode]'

# Replace default with 'typenames'
typenames(Optional[BaseNode], remove_modules=["typenames"])
#> 'typing.Optional[BaseNode]'

# Extend default with 'typenames'
typenames(
    Optional[BaseNode],
    remove_modules=DEFAULT_REMOVE_MODULES + ["typenames"],
)
#> 'Optional[BaseNode]'

To remove all module names, you can use REMOVE_ALL_MODULES, which contains the pattern re.compile(r"^(<?\w+>?\.)+").

Annotated (include_extras)

This option controls whether to render Annotated and the extra metadata. typing.Annotated is a typing special form introduced in Python 3.9 and originally specified by PEP 593. Many libraries like Pydantic, FastAPI, and Typer use it to attach metadata to type annotations that are used at runtime.

By default, typenames will not render Annotated and extra metadata. Set include_extras=True to render them.

from typing import Annotated
from typenames import typenames

typenames(Annotated[int, "some metadata"])
#> 'int'
typenames(Annotated[int, "some metadata"], include_extras=True)
#> "Annotated[int, 'some metadata']"

Type Aliases (PEP 695)

typenames recognizes PEP 695 type aliases, i.e., ones defined with the type statement (Python 3.12+) or constructed directly with typing.TypeAliasType / typing_extensions.TypeAliasType. An alias renders as its name, with the same remove_modules handling applied to its module prefix as any other type. typenames does not expand aliases to show what they point to.

from typenames import typenames

type MyAlias = list[int]

typenames(MyAlias)
#> 'MyAlias'
typenames(list[MyAlias])
#> 'list[MyAlias]'

Reproducible examples created by reprexlite.

Metadata

Release files for typenames 2.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for typenames 2.2.0
File Size Uploaded Provenance Actions
typenames-2.2.0.tar.gz 11.6 kB With provenance Details for typenames-2.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for typenames 2.2.0
File Interpreter ABI Platform Actions
typenames-2.2.0-py3-none-any.whl Python 3 none any Details for typenames-2.2.0-py3-none-any.whl

Total release size: 22.9 kB

Release files / typenames-2.2.0.tar.gz

Download URL typenames-2.2.0.tar.gz
Size 11.6 kB
Tags Source
SHA-256 checksum
How to use checksums
7d64e8432e7ed0cb583afd1b6d44bcb3c8d55d0b76f69e5f58c1a251131aa42a
BLAKE2b-256 checksum
How to use checksums
d5f61518a2d1669ae4b268824d1e5542d7e82eddca52afc80215b23ad8baf7d3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 2, 2026.

Transparency log

Release files / typenames-2.2.0-py3-none-any.whl

Download URL typenames-2.2.0-py3-none-any.whl
Size 11.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
174fa02d90dc63dc398e27c5d03cacc3972eb39f6bd962248159d080cb8278c4
BLAKE2b-256 checksum
How to use checksums
065e957883198b94579a4bef29367673788db8cbe8119089ac898bebfd7aff07
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 2, 2026.

Transparency log

Security for typenames 2.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for typenames-2.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 2, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page