Explicit return types in function documentation

Function return type annotations were introduced in Python 3.5 as part of PEP 484.
A lot of Python library docs don’t explicitly specify return types and if they do, they specify it as one of the sentences in the description.
For example, is there any reason json.dumps says:

json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

instead of:

json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) -> str

or something similar.
In json functions, it is obviously stated what’s the return type or possible return type but for many docs, it’s not obvious.
Maybe we should add known return types for built-in libraries in the docs.

Is there any discussion, ticket, tracker or topic opened for this before?

3 Likes

We use typeshed for stdlib type annotations instead of annotating the docs. Users can then use mypy or any other type checker.

While I understand that it may be easier for some functions (not everyone uses an IDE that tells them the return type & co, and not everyone uses a type checker), sometimes we also want to hide the exact type being returned as it’s an internal one.

Instead, if there are places where the exact return type is important or is missing, then those places must be fixed in the docs (and you’re free to open a meta issue for them if none already exists) by adding a sentence in the description.

Adding type annotations in the docs also hinders readability in general (there are more symbols to parse). One might note that some docs are “lightweight” on purpose.

See also Type annotations in the stdlib