Skip to content

Commit 830c949

Browse files
feat(mathy_pydoc): preserve Optional types in docs
1 parent dbcc9a6 commit 830c949

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

libraries/mathy_pydoc_markdown/pydocmd/loader.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import inspect
3030
import types
3131
from typing import Callable, Optional, List, Any
32+
import re
3233

3334
function_types = (
3435
types.FunctionType,
@@ -40,6 +41,11 @@
4041
if hasattr(types, "UnboundMethodType"):
4142
function_types += (types.UnboundMethodType,)
4243

44+
# Used to replace verbose type reported, e.g. "Union[str, NoneType]" with the simpler
45+
# form that is usually used in code "Optional[str]"
46+
optional_match = r"(.*)Union\[(.*),\sNoneType\](.*)"
47+
optional_replace = r"\1Optional[\2]\3"
48+
4349

4450
def trim(docstring):
4551
if not docstring:
@@ -169,6 +175,10 @@ def get_callable_placeholder(
169175
annotation = inspect.formatannotation(p.annotation)
170176
if p.default is not inspect._empty: # type: ignore
171177
default_value = str(p.default)
178+
179+
# The type annotations expand Optional[T] to Union[T, NoneType]
180+
while re.search(optional_match, annotation) is not None:
181+
annotation = re.sub(optional_match, optional_replace, annotation)
172182
params.append(CallableArg(p.name, annotation, default_value))
173183

174184
return_annotation = None

libraries/mathy_pydoc_markdown/testmodule/__init__.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22

33

44
def a_function_with_types(
5-
inputs: List[Dict[str, Any]], auxiliary: Tuple[Optional[str]], final: int = 3
5+
optional: Optional[str],
6+
nested_optional: Optional[Tuple[Optional[str], Optional[int]]],
7+
inputs: List[Dict[str, Any]],
8+
auxiliary: Tuple[Optional[str]],
9+
final: int = 3,
610
) -> List[str]:
711
"""Sweet typed function"""
812
pass

0 commit comments

Comments
 (0)