Skip to content

Instantly share code, notes, and snippets.

@fhightower
Last active February 23, 2021 22:23
Show Gist options
  • Save fhightower/55370897d6901486425eba3cb5438137 to your computer and use it in GitHub Desktop.
Save fhightower/55370897d6901486425eba3cb5438137 to your computer and use it in GitHub Desktop.
Convert python type hints to plain english
def _get_name(ele):
if hasattr(ele, '_name'):
return ele._name
else:
return ele.__name__
def f(a):
# todo: handle optional
# todo: handle union
# todo: re-add indefinite articles
# todo: make the outputs plural as appropriate
# todo: handle ... in tuples
# todo: handle callables
# todo: print length for tuple (e.g. "Tuple with {len(args)} elements...")
name = _get_name(a)
print(f'{name}', end=' ')
if hasattr(a, '__args__') and any(a.__args__):
if name == 'List':
print('of', end=' ')
else:
print('with', end=' ')
if name == 'Dict':
print(f'keys that are', end=' ')
f(a.__args__[0])
print(f'and values that are', end=' ')
f(a.__args__[1])
else:
for index, arg in enumerate(a.__args__):
f(arg)
if index < len(a.__args__) - 1:
print('and', end=' ')
f(Tuple[int, Dict[str, Any]]) # Tuple with int and Dict with keys that are str and values that are Any
f(Dict[int, Tuple[str, Any]]) # Dict with keys that are int and values that are Tuple with str and Any
f(Tuple[str, Any, Dict[int, Tuple[int, Dict[str, str]]]]) # Tuple with str and Any and Dict with keys that are int and values that are Tuple with int and Dict with keys that are str and values that are str
f(Tuple[str, Any, Dict[int, Tuple[int, List[str]]]]) # Tuple with str and Any and Dict with keys that are int and values that are Tuple with int and List of str
f(List[Dict[int, Tuple[int, List[str]]]]) # List of Dict with keys that are int and values that are Tuple with int and List of str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment