|
16 | 16 | from collections.abc import Callable, Iterable
|
17 | 17 | from difflib import SequenceMatcher
|
18 | 18 | from enum import Enum
|
19 |
| -from typing import TYPE_CHECKING, Any, TextIO, TypeVar, Union, cast, get_type_hints |
| 19 | +from typing import TYPE_CHECKING, Any, TextIO, TypeVar, Union, cast |
20 | 20 |
|
21 | 21 | from . import constants
|
22 | 22 | from .argparse_custom import ChoicesProviderFunc, CompleterFunc
|
@@ -1245,24 +1245,21 @@ def suggest_similar(
|
1245 | 1245 |
|
1246 | 1246 |
|
1247 | 1247 | def get_types(func_or_method: Callable[..., Any]) -> tuple[dict[str, Any], Any]:
|
1248 |
| - """Use typing.get_type_hints() to extract type hints for parameters and return value. |
| 1248 | + """Use inspect.get_annotations() to extract type hints for parameters and return value. |
1249 | 1249 |
|
1250 |
| - This exists because the inspect module doesn't have a safe way of doing this that works |
1251 |
| - both with and without importing annotations from __future__ until Python 3.10. |
1252 |
| -
|
1253 |
| - TODO: Once cmd2 only supports Python 3.10+, change to use inspect.get_annotations(eval_str=True) |
| 1250 | + This is a thin convenience wrapper around inspect.get_annotations() that treats the return value |
| 1251 | + annotation separately. |
1254 | 1252 |
|
1255 | 1253 | :param func_or_method: Function or method to return the type hints for
|
1256 |
| - :return tuple with first element being dictionary mapping param names to type hints |
1257 |
| - and second element being return type hint, unspecified, returns None |
| 1254 | + :return: tuple with first element being dictionary mapping param names to type hints |
| 1255 | + and second element being the return type hint or None if there is no return value type hint |
| 1256 | + :raises ValueError: if the `func_or_method` argument is not a valid object to pass to `inspect.get_annotations` |
1258 | 1257 | """
|
1259 | 1258 | try:
|
1260 |
| - type_hints = get_type_hints(func_or_method) # Get dictionary of type hints |
| 1259 | + type_hints = inspect.get_annotations(func_or_method, eval_str=True) # Get dictionary of type hints |
1261 | 1260 | except TypeError as exc:
|
1262 | 1261 | raise ValueError("Argument passed to get_types should be a function or method") from exc
|
1263 | 1262 | ret_ann = type_hints.pop('return', None) # Pop off the return annotation if it exists
|
1264 | 1263 | if inspect.ismethod(func_or_method):
|
1265 | 1264 | type_hints.pop('self', None) # Pop off `self` hint for methods
|
1266 |
| - if ret_ann is type(None): |
1267 |
| - ret_ann = None # Simplify logic to just return None instead of NoneType |
1268 | 1265 | return type_hints, ret_ann
|
0 commit comments