Formatting guidelines for type aliases

Viewed 179

What would be the correct way to format the name of a type alias—intended to be local to its module—according to the PEP8 style guide?

# mymodule.py
from typing import TypeAlias

mytype: TypeAlias = int

def f() -> mytype:
    return mytype()

def g() -> mytype:
    return mytype()

Should mytype be formatted in CapWords because it introduces a new type similar to creating new classes? Or, should mytype be formatted in all caps because it is treated similarly to a constant?

Is there a way to differentiate between type aliases that will remain unchanged (constant) throughout the lifetime of the program and ones that can change (similar to the Final annotation for constants)?

Also, should mytype be prefixed with an underscore (as in _mytype) to indicate that the type alias shouldn't be used outside this module?

1 Answers

The PEP Style Guide does not have any explicit guidance on how to format TypeAliases. The guide does contain some rules on type variables, but that's not quite what you're asking for.


The next best resource I could find was Google's Python Style Guide, which does happen to contain some guidance on how to name TypeAliases:

3.19.6 Type Aliases

You can declare aliases of complex types. The name of an alias should be CapWorded. If the alias is used only in this module, it should be _Private.

For example, if the name of the module together with the name of the type is too long:

_ShortName = module_with_long_name.TypeWithLongName
ComplexMap = Mapping[str, List[Tuple[int, int]]]

Other examples are complex nested types and multiple return variables from a function (as a tuple).

Under this, the name of your type alias should be MyType if used across multiple modules, or _MyType if only used in the module that it is declared in.


With all of this being said, remember that consistency with the existing codebase is what's most important. As the PEP style guide states:

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is the most important.

Related