问题
Suppose I have a function with a docstring where I declare the return type as a tuple with two strings:
def foo():
"""
Returns:
Tuple[str, str]: Tuple of first name and last name
"""
Am I supposed to import Tuple
from typing
if I don't use it anywhere except for in docstrings?
回答1:
PyCharm's docstring support for type hints does not actually use typing
. You do not need to import the module.
The typing
module is only there to support the fact that annotations are executed at runtime; for a statement starting with def foo() -> Tuple[str, str]:
, Python will actually evaluate the expression Tuple[str, str]
so expects to be able to resolve the names. (As of Python 3.7 you can disable (or rather, postpone) the evaluation with from __future__ import annotations
).
But a docstring is not evaluated, normally, and is not expected to be able to contain runnable Python code.
Unless you have a hard requirement to put the type info in the docstring, I'd stick with actual annotations:
from typing import Tuple
# type aliases
firstname = str
lastname = str
def foo() -> Tuple[firstname, lastname]:
"""Descriptive line documenting this function's purpose"""
# ...
回答2:
You don't. Docstrings are just comments. They are ignored by the interpreter. So, don't import it, otherwise code checking tools (eg. pylint
) will complain about unused imports.
However, it would probably be better to use backticks inside your docstring for parts that are actual code. eg
"""
Returns:
`Tuple[str, str]`: Tuple of first name and last name
"""
That way, doc-generation tools know that it's actual code, and can format it properly.
来源:https://stackoverflow.com/questions/52835740/using-typing-module-in-docstring