hustas88
hustas88

Reputation: 307

Type annotation in Sphinx docstring

how to write the :type annotation in Python in case the argument can have different types?

    """
    :type param_name: type1|type2
    """

or

    """
    :type param_name: type1 / type2
    """

PyCharm accepts the 2nd variant

Upvotes: 0

Views: 764

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124238

You are using the Sphinx project notation, which incidentally was rejected for inclusion in the PEP 484 -- Type Hints proposal.

:type is an info field list, and there isn't really all that much of a formal specification for these. The documentation example uses or:

:type priority: integer or None

but note that integer isn't a formal type, nor is None (it is a singleton object).

These are documentation constructs, not type hints, really. That PyCharm supports these at all is nice, but these are not a Python standard.

I'd stick with proper type annotations instead. That means using a Union type:

Union[type1, type2]

You can put these in a # type: comment if you need to support Python 2.

Upvotes: 1

Related Questions