Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/sphinx-doc/sphinx.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTakeshi KOMIYA <i.tkomiya@gmail.com>2021-01-31 16:05:29 +0300
committerTakeshi KOMIYA <i.tkomiya@gmail.com>2021-01-31 17:38:36 +0300
commit7318d1dfd4ba39d9aa74f718bb02fba2ded9648f (patch)
tree646f96437e377c0c362ef659cd33116078cd0d6e /sphinx/util
parentbe20f178924fbb610f69cd30ef25a78aa1a892df (diff)
autodoc: Support type union operator (PEP-604) (refs: #8775)
Upgrade autodoc to support type union operator introduced in PEP-604. It's available only with python 3.10+.
Diffstat (limited to 'sphinx/util')
-rw-r--r--sphinx/util/typing.py19
1 files changed, 19 insertions, 0 deletions
diff --git a/sphinx/util/typing.py b/sphinx/util/typing.py
index e85c40cdf..5cee1834a 100644
--- a/sphinx/util/typing.py
+++ b/sphinx/util/typing.py
@@ -30,6 +30,11 @@ else:
ref = _ForwardRef(self.arg)
return ref._eval_type(globalns, localns)
+if sys.version_info > (3, 10):
+ from types import Union as types_Union
+else:
+ types_Union = None
+
if False:
# For type annotation
from typing import Type # NOQA # for python3.5.1
@@ -100,6 +105,12 @@ def restify(cls: Optional["Type"]) -> str:
return ':class:`struct.Struct`'
elif inspect.isNewType(cls):
return ':class:`%s`' % cls.__name__
+ elif types_Union and isinstance(cls, types_Union):
+ if len(cls.__args__) > 1 and None in cls.__args__:
+ args = ' | '.join(restify(a) for a in cls.__args__ if a)
+ return 'Optional[%s]' % args
+ else:
+ return ' | '.join(restify(a) for a in cls.__args__)
elif cls.__module__ in ('__builtin__', 'builtins'):
return ':class:`%s`' % cls.__name__
else:
@@ -336,6 +347,8 @@ def _stringify_py37(annotation: Any) -> str:
elif hasattr(annotation, '__origin__'):
# instantiated generic provided by a user
qualname = stringify(annotation.__origin__)
+ elif types_Union and isinstance(annotation, types_Union): # types.Union (for py3.10+)
+ qualname = 'types.Union'
else:
# we weren't able to extract the base type, appending arguments would
# only make them appear twice
@@ -355,6 +368,12 @@ def _stringify_py37(annotation: Any) -> str:
else:
args = ', '.join(stringify(a) for a in annotation.__args__)
return 'Union[%s]' % args
+ elif qualname == 'types.Union':
+ if len(annotation.__args__) > 1 and None in annotation.__args__:
+ args = ' | '.join(stringify(a) for a in annotation.__args__ if a)
+ return 'Optional[%s]' % args
+ else:
+ return ' | '.join(stringify(a) for a in annotation.__args__)
elif qualname == 'Callable':
args = ', '.join(stringify(a) for a in annotation.__args__[:-1])
returns = stringify(annotation.__args__[-1])