From: Vladimír Vondruš Date: Fri, 27 Sep 2019 18:19:09 +0000 (+0200) Subject: documentation: fix a crashy corner case with the typing module. X-Git-Url: https://www.chiark.greenend.org.uk/ucgi/~cjwatson/git?a=commitdiff_plain;h=0d63ac9045568bfb3f8455caac0aab6db32546fc;p=blog.git documentation: fix a crashy corner case with the typing module. WHY IS IT SUCH A DUMPSTER FIRE --- diff --git a/documentation/python.py b/documentation/python.py index ece774ee..21bb2e9a 100755 --- a/documentation/python.py +++ b/documentation/python.py @@ -1094,8 +1094,11 @@ def extract_annotation(state: State, referrer_path: List[str], annotation) -> Tu elif (hasattr(annotation, '__module__') and annotation.__module__ == 'typing'): # Optional or Union, handle those first if hasattr(annotation, '__origin__') and annotation.__origin__ is typing.Union: - # FOR SOME REASON `annotation.__args__[1] is None` is always False - if len(annotation.__args__) == 2 and isinstance(None, annotation.__args__[1]): + # FOR SOME REASON `annotation.__args__[1] is None` is always False, + # so we have to use isinstance(). HOWEVER, we *can't* use + # isinstance if it's a "bracketed" type -- it'll die. So check that + # first. + if len(annotation.__args__) == 2 and not hasattr(annotation.__args__[1], '__args__') and isinstance(None, annotation.__args__[1]): name = 'typing.Optional' args = annotation.__args__[:1] else: diff --git a/documentation/test_python/inspect_annotations/inspect_annotations.html b/documentation/test_python/inspect_annotations/inspect_annotations.html index 393138c1..70c0960a 100644 --- a/documentation/test_python/inspect_annotations/inspect_annotations.html +++ b/documentation/test_python/inspect_annotations/inspect_annotations.html @@ -105,6 +105,10 @@ def annotation_union(a: typing.Union[float, int])
Annotation with the Union type
+
+ def annotation_union_second_bracketed(a: typing.Union[float, typing.List[int]]) +
+
Annotation with the Union type and second type bracketed, where we can't use isinstance
def args_kwargs(a, b, *args, **kwargs)
diff --git a/documentation/test_python/inspect_annotations/inspect_annotations.py b/documentation/test_python/inspect_annotations/inspect_annotations.py index bc38f81b..e4b65973 100644 --- a/documentation/test_python/inspect_annotations/inspect_annotations.py +++ b/documentation/test_python/inspect_annotations/inspect_annotations.py @@ -63,6 +63,9 @@ def annotation_generic(a: List[_T]) -> _T: def annotation_optional(a: Optional[float]): """Annotation with the Optional type""" +def annotation_union_second_bracketed(a: Union[float, List[int]]): + """Annotation with the Union type and second type bracketed, where we can't use isinstance""" + def annotation_callable(a: Callable[[float, int], str]): """Annotation with the Callable type"""