82
82
import types
83
83
import warnings
84
84
from collections import OrderedDict , defaultdict
85
+ from collections .abc import Iterable , Mapping
85
86
from itertools import permutations , zip_longest
86
87
from keyword import iskeyword as _iskeyword
87
88
from string import ascii_lowercase
91
92
Any ,
92
93
Callable ,
93
94
DefaultDict ,
94
- Dict ,
95
95
ForwardRef ,
96
- Iterable ,
97
- List ,
98
- Mapping ,
99
96
NamedTuple ,
100
97
Optional ,
101
- Set ,
102
- Tuple ,
103
- Type ,
104
98
TypeVar ,
105
99
Union ,
106
100
get_args ,
@@ -156,8 +150,8 @@ def test_{test_kind}_{func_name}({arg_names}){return_annotation}:
156
150
reject()
157
151
""" .strip ()
158
152
159
- Except = Union [Type [Exception ], Tuple [ Type [Exception ], ...]]
160
- ImportSet = Set [Union [str , Tuple [str , str ]]]
153
+ Except = Union [type [Exception ], tuple [ type [Exception ], ...]]
154
+ ImportSet = set [Union [str , tuple [str , str ]]]
161
155
_quietly_settings = settings (
162
156
database = None ,
163
157
deadline = None ,
@@ -166,7 +160,7 @@ def test_{test_kind}_{func_name}({arg_names}){return_annotation}:
166
160
)
167
161
168
162
169
- def _dedupe_exceptions (exc : Tuple [ Type [Exception ], ...]) -> Tuple [ Type [Exception ], ...]:
163
+ def _dedupe_exceptions (exc : tuple [ type [Exception ], ...]) -> tuple [ type [Exception ], ...]:
170
164
# This is reminiscent of de-duplication logic I wrote for flake8-bugbear,
171
165
# but with access to the actual objects we can just check for subclasses.
172
166
# This lets us print e.g. `Exception` instead of `(Exception, OSError)`.
@@ -177,7 +171,7 @@ def _dedupe_exceptions(exc: Tuple[Type[Exception], ...]) -> Tuple[Type[Exception
177
171
return tuple (sorted (uniques , key = lambda e : e .__name__ ))
178
172
179
173
180
- def _check_except (except_ : Except ) -> Tuple [ Type [Exception ], ...]:
174
+ def _check_except (except_ : Except ) -> tuple [ type [Exception ], ...]:
181
175
if isinstance (except_ , tuple ):
182
176
for i , e in enumerate (except_ ):
183
177
if not isinstance (e , type ) or not issubclass (e , Exception ):
@@ -194,7 +188,7 @@ def _check_except(except_: Except) -> Tuple[Type[Exception], ...]:
194
188
return (except_ ,)
195
189
196
190
197
- def _exception_string (except_ : Tuple [ Type [Exception ], ...]) -> Tuple [ImportSet , str ]:
191
+ def _exception_string (except_ : tuple [ type [Exception ], ...]) -> tuple [ImportSet , str ]:
198
192
if not except_ :
199
193
return set (), ""
200
194
exceptions = []
@@ -215,7 +209,7 @@ def _check_style(style: str) -> None:
215
209
raise InvalidArgument (f"Valid styles are 'pytest' or 'unittest', got { style !r} " )
216
210
217
211
218
- def _exceptions_from_docstring (doc : str ) -> Tuple [ Type [Exception ], ...]:
212
+ def _exceptions_from_docstring (doc : str ) -> tuple [ type [Exception ], ...]:
219
213
"""Return a tuple of exceptions that the docstring says may be raised.
220
214
221
215
Note that we ignore non-builtin exception types for simplicity, as this is
@@ -250,7 +244,7 @@ def _type_from_doc_fragment(token: str) -> Optional[type]:
250
244
if elems is None and elem_token .endswith ("s" ):
251
245
elems = _type_from_doc_fragment (elem_token [:- 1 ])
252
246
if elems is not None and coll_token in ("list" , "sequence" , "collection" ):
253
- return List [elems ] # type: ignore
247
+ return list [elems ] # type: ignore
254
248
# This might be e.g. "array-like of float"; arrays is better than nothing
255
249
# even if we can't conveniently pass a generic type around.
256
250
return _type_from_doc_fragment (coll_token )
@@ -451,7 +445,7 @@ def _guess_strategy_by_argname(name: str) -> st.SearchStrategy:
451
445
return st .nothing ()
452
446
453
447
454
- def _get_params_builtin_fn (func : Callable ) -> List [inspect .Parameter ]:
448
+ def _get_params_builtin_fn (func : Callable ) -> list [inspect .Parameter ]:
455
449
if (
456
450
isinstance (func , (types .BuiltinFunctionType , types .BuiltinMethodType ))
457
451
and hasattr (func , "__doc__" )
@@ -483,7 +477,7 @@ def _get_params_builtin_fn(func: Callable) -> List[inspect.Parameter]:
483
477
return []
484
478
485
479
486
- def _get_params_ufunc (func : Callable ) -> List [inspect .Parameter ]:
480
+ def _get_params_ufunc (func : Callable ) -> list [inspect .Parameter ]:
487
481
if _is_probably_ufunc (func ):
488
482
# `inspect.signature` results vary for ufunc objects, but we can work out
489
483
# what the required parameters would look like if it was reliable.
@@ -498,7 +492,7 @@ def _get_params_ufunc(func: Callable) -> List[inspect.Parameter]:
498
492
return []
499
493
500
494
501
- def _get_params (func : Callable ) -> Dict [str , inspect .Parameter ]:
495
+ def _get_params (func : Callable ) -> dict [str , inspect .Parameter ]:
502
496
"""Get non-vararg parameters of `func` as an ordered dict."""
503
497
try :
504
498
params = list (get_signature (func ).parameters .values ())
@@ -522,7 +516,7 @@ def _get_params(func: Callable) -> Dict[str, inspect.Parameter]:
522
516
523
517
def _params_to_dict (
524
518
params : Iterable [inspect .Parameter ],
525
- ) -> Dict [str , inspect .Parameter ]:
519
+ ) -> dict [str , inspect .Parameter ]:
526
520
var_param_kinds = (inspect .Parameter .VAR_POSITIONAL , inspect .Parameter .VAR_KEYWORD )
527
521
return OrderedDict ((p .name , p ) for p in params if p .kind not in var_param_kinds )
528
522
@@ -548,7 +542,7 @@ def _with_any_registered():
548
542
549
543
def _get_strategies (
550
544
* funcs : Callable , pass_result_to_next_func : bool = False
551
- ) -> Dict [str , st .SearchStrategy ]:
545
+ ) -> dict [str , st .SearchStrategy ]:
552
546
"""Return a dict of strategies for the union of arguments to `funcs`.
553
547
554
548
If `pass_result_to_next_func` is True, assume that the result of each function
@@ -558,7 +552,7 @@ def _get_strategies(
558
552
This dict is used to construct our call to the `@given(...)` decorator.
559
553
"""
560
554
assert funcs , "Must pass at least one function"
561
- given_strategies : Dict [str , st .SearchStrategy ] = {}
555
+ given_strategies : dict [str , st .SearchStrategy ] = {}
562
556
for i , f in enumerate (funcs ):
563
557
params = _get_params (f )
564
558
if pass_result_to_next_func and i >= 1 :
@@ -735,7 +729,7 @@ def _valid_syntax_repr(strategy):
735
729
736
730
# When we ghostwrite for a module, we want to treat that as the __module__ for
737
731
# each function, rather than whichever internal file it was actually defined in.
738
- KNOWN_FUNCTION_LOCATIONS : Dict [object , str ] = {}
732
+ KNOWN_FUNCTION_LOCATIONS : dict [object , str ] = {}
739
733
740
734
741
735
def _get_module_helper (obj ):
@@ -832,13 +826,13 @@ def _make_test_body(
832
826
* funcs : Callable ,
833
827
ghost : str ,
834
828
test_body : str ,
835
- except_ : Tuple [ Type [Exception ], ...],
829
+ except_ : tuple [ type [Exception ], ...],
836
830
assertions : str = "" ,
837
831
style : str ,
838
832
given_strategies : Optional [Mapping [str , Union [str , st .SearchStrategy ]]] = None ,
839
833
imports : Optional [ImportSet ] = None ,
840
834
annotate : bool ,
841
- ) -> Tuple [ImportSet , str ]:
835
+ ) -> tuple [ImportSet , str ]:
842
836
# A set of modules to import - we might add to this later. The import code
843
837
# is written later, so we can have one import section for multiple magic()
844
838
# test functions.
@@ -899,7 +893,7 @@ def _make_test_body(
899
893
def _annotate_args (
900
894
argnames : Iterable [str ], funcs : Iterable [Callable ], imports : ImportSet
901
895
) -> Iterable [str ]:
902
- arg_parameters : DefaultDict [str , Set [Any ]] = defaultdict (set )
896
+ arg_parameters : DefaultDict [str , set [Any ]] = defaultdict (set )
903
897
for func in funcs :
904
898
try :
905
899
params = tuple (get_signature (func , eval_str = True ).parameters .values ())
@@ -922,7 +916,7 @@ def _annotate_args(
922
916
923
917
class _AnnotationData (NamedTuple ):
924
918
type_name : str
925
- imports : Set [str ]
919
+ imports : set [str ]
926
920
927
921
928
922
def _parameters_to_annotation_name (
@@ -949,7 +943,7 @@ def _parameters_to_annotation_name(
949
943
950
944
951
945
def _join_generics (
952
- origin_type_data : Optional [Tuple [str , Set [str ]]],
946
+ origin_type_data : Optional [tuple [str , set [str ]]],
953
947
annotations : Iterable [Optional [_AnnotationData ]],
954
948
) -> Optional [_AnnotationData ]:
955
949
if origin_type_data is None :
@@ -976,9 +970,9 @@ def _join_generics(
976
970
977
971
def _join_argument_annotations (
978
972
annotations : Iterable [Optional [_AnnotationData ]],
979
- ) -> Optional [Tuple [ List [str ], Set [str ]]]:
980
- imports : Set [str ] = set ()
981
- arg_types : List [str ] = []
973
+ ) -> Optional [tuple [ list [str ], set [str ]]]:
974
+ imports : set [str ] = set ()
975
+ arg_types : list [str ] = []
982
976
983
977
for annotation in annotations :
984
978
if annotation is None :
@@ -1134,10 +1128,10 @@ def _is_probably_ufunc(obj):
1134
1128
)
1135
1129
1136
1130
1137
- def _get_testable_functions (thing : object ) -> Dict [str , Callable ]:
1131
+ def _get_testable_functions (thing : object ) -> dict [str , Callable ]:
1138
1132
by_name = {}
1139
1133
if callable (thing ):
1140
- funcs : List [Optional [Any ]] = [thing ]
1134
+ funcs : list [Optional [Any ]] = [thing ]
1141
1135
elif isinstance (thing , types .ModuleType ):
1142
1136
if hasattr (thing , "__all__" ):
1143
1137
funcs = [getattr (thing , name , None ) for name in thing .__all__ ]
@@ -1732,10 +1726,10 @@ def _make_binop_body(
1732
1726
commutative : bool = True ,
1733
1727
identity : Union [X , EllipsisType , None ] = ...,
1734
1728
distributes_over : Optional [Callable [[X , X ], X ]] = None ,
1735
- except_ : Tuple [ Type [Exception ], ...],
1729
+ except_ : tuple [ type [Exception ], ...],
1736
1730
style : str ,
1737
1731
annotate : bool ,
1738
- ) -> Tuple [ImportSet , str ]:
1732
+ ) -> tuple [ImportSet , str ]:
1739
1733
strategies = _get_strategies (func )
1740
1734
operands , b = (strategies .pop (p ) for p in list (_get_params (func ))[:2 ])
1741
1735
if repr (operands ) != repr (b ):
0 commit comments