Skip to content
This repository was archived by the owner on Feb 13, 2025. It is now read-only.

Commit 0c5f47f

Browse files
committed
Issue python#28556: various style fixes for typing.py (3.5->3.6)
2 parents 78034c8 + d7adfe1 commit 0c5f47f

File tree

2 files changed

+68
-36
lines changed

2 files changed

+68
-36
lines changed

Lib/test/test_typing.py

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -701,7 +701,7 @@ class Node(Generic[T]): ...
701701
self.assertFalse(naive_generic_check(Node[str](), Node[int]))
702702
self.assertFalse(naive_generic_check(Node[str](), List))
703703
with self.assertRaises(NotImplementedError):
704-
naive_generic_check([1,2,3], Node[int])
704+
naive_generic_check([1, 2, 3], Node[int])
705705

706706
def naive_list_base_check(obj, tp):
707707
# Check if list conforms to a List subclass
@@ -773,7 +773,10 @@ def test_extended_generic_rules_repr(self):
773773
def test_generic_forward_ref(self):
774774
def foobar(x: List[List['CC']]): ...
775775
class CC: ...
776-
self.assertEqual(get_type_hints(foobar, globals(), locals()), {'x': List[List[CC]]})
776+
self.assertEqual(
777+
get_type_hints(foobar, globals(), locals()),
778+
{'x': List[List[CC]]}
779+
)
777780
T = TypeVar('T')
778781
AT = Tuple[T, ...]
779782
def barfoo(x: AT): ...
@@ -1094,6 +1097,7 @@ class D(C):
10941097
with self.assertRaises(Exception):
10951098
D[T]
10961099

1100+
10971101
class ClassVarTests(BaseTestCase):
10981102

10991103
def test_basics(self):
@@ -1316,9 +1320,6 @@ def test_default_globals(self):
13161320

13171321
class OverloadTests(BaseTestCase):
13181322

1319-
def test_overload_exists(self):
1320-
from typing import overload
1321-
13221323
def test_overload_fails(self):
13231324
from typing import overload
13241325

@@ -1381,6 +1382,10 @@ def __anext__(self) -> T_a:
13811382
exec(ASYNCIO_TESTS)
13821383
except ImportError:
13831384
ASYNCIO = False
1385+
else:
1386+
# fake names for the sake of static analysis
1387+
asyncio = None
1388+
AwaitableWrapper = AsyncIteratorWrapper = object
13841389

13851390
PY36 = sys.version_info[:2] >= (3, 6)
13861391

@@ -1408,9 +1413,14 @@ class CoolEmployeeWithDefault(NamedTuple):
14081413

14091414
if PY36:
14101415
exec(PY36_TESTS)
1416+
else:
1417+
# fake names for the sake of static analysis
1418+
ann_module = ann_module2 = ann_module3 = None
1419+
A = B = CSub = G = CoolEmployee = CoolEmployeeWithDefault = object
14111420

14121421
gth = get_type_hints
14131422

1423+
14141424
class GetTypeHintTests(BaseTestCase):
14151425
def test_get_type_hints_from_various_objects(self):
14161426
# For invalid objects should fail with TypeError (not AttributeError etc).
@@ -1423,7 +1433,8 @@ def test_get_type_hints_from_various_objects(self):
14231433

14241434
@skipUnless(PY36, 'Python 3.6 required')
14251435
def test_get_type_hints_modules(self):
1426-
self.assertEqual(gth(ann_module), {1: 2, 'f': Tuple[int, int], 'x': int, 'y': str})
1436+
ann_module_type_hints = {1: 2, 'f': Tuple[int, int], 'x': int, 'y': str}
1437+
self.assertEqual(gth(ann_module), ann_module_type_hints)
14271438
self.assertEqual(gth(ann_module2), {})
14281439
self.assertEqual(gth(ann_module3), {})
14291440

@@ -1926,7 +1937,7 @@ class ProUser(User): pass
19261937
def new_user(user_class: Type[User]) -> User:
19271938
return user_class()
19281939

1929-
joe = new_user(BasicUser)
1940+
new_user(BasicUser)
19301941

19311942
def test_type_typevar(self):
19321943

@@ -1939,7 +1950,7 @@ class ProUser(User): pass
19391950
def new_user(user_class: Type[U]) -> U:
19401951
return user_class()
19411952

1942-
joe = new_user(BasicUser)
1953+
new_user(BasicUser)
19431954

19441955
def test_type_optional(self):
19451956
A = Optional[Type[BaseException]]
@@ -2102,8 +2113,8 @@ def test_basics(self):
21022113
self.assertIsInstance(mat, Match)
21032114

21042115
# these should just work
2105-
p = Pattern[Union[str, bytes]]
2106-
m = Match[Union[bytes, str]]
2116+
Pattern[Union[str, bytes]]
2117+
Match[Union[bytes, str]]
21072118

21082119
def test_errors(self):
21092120
with self.assertRaises(TypeError):

Lib/typing.py

Lines changed: 47 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,8 @@ def _qualname(x):
9797

9898

9999
def _trim_name(nm):
100-
if nm.startswith('_') and nm not in ('_TypeAlias',
101-
'_ForwardRef', '_TypingBase', '_FinalTypingBase'):
100+
whitelist = ('_TypeAlias', '_ForwardRef', '_TypingBase', '_FinalTypingBase')
101+
if nm.startswith('_') and nm not in whitelist:
102102
nm = nm[1:]
103103
return nm
104104

@@ -355,13 +355,17 @@ def _type_check(arg, msg):
355355
return type(None)
356356
if isinstance(arg, str):
357357
arg = _ForwardRef(arg)
358-
if (isinstance(arg, _TypingBase) and type(arg).__name__ == '_ClassVar' or
359-
not isinstance(arg, (type, _TypingBase)) and not callable(arg)):
358+
if (
359+
isinstance(arg, _TypingBase) and type(arg).__name__ == '_ClassVar' or
360+
not isinstance(arg, (type, _TypingBase)) and not callable(arg)
361+
):
360362
raise TypeError(msg + " Got %.100r." % (arg,))
361363
# Bare Union etc. are not valid as type arguments
362-
if (type(arg).__name__ in ('_Union', '_Optional')
363-
and not getattr(arg, '__origin__', None)
364-
or isinstance(arg, TypingMeta) and _gorg(arg) in (Generic, _Protocol)):
364+
if (
365+
type(arg).__name__ in ('_Union', '_Optional') and
366+
not getattr(arg, '__origin__', None) or
367+
isinstance(arg, TypingMeta) and _gorg(arg) in (Generic, _Protocol)
368+
):
365369
raise TypeError("Plain %s is not valid as type argument" % arg)
366370
return arg
367371

@@ -455,7 +459,7 @@ def longest(x: A, y: A) -> A:
455459
'__covariant__', '__contravariant__')
456460

457461
def __init__(self, name, *constraints, bound=None,
458-
covariant=False, contravariant=False):
462+
covariant=False, contravariant=False):
459463
super().__init__(name, *constraints, bound=bound,
460464
covariant=covariant, contravariant=contravariant)
461465
self.__name__ = name
@@ -563,7 +567,7 @@ def _subs_tree(cls, tvars=None, args=None):
563567
# ... then continue replacing down the origin chain.
564568
for ocls in orig_chain:
565569
new_tree_args = []
566-
for i, arg in enumerate(ocls.__args__):
570+
for arg in ocls.__args__:
567571
new_tree_args.append(_replace_arg(arg, ocls.__parameters__, tree_args))
568572
tree_args = new_tree_args
569573
return tree_args
@@ -631,6 +635,7 @@ def _tp_cache(func):
631635

632636
cached = functools.lru_cache()(func)
633637
_cleanups.append(cached.cache_clear)
638+
634639
@functools.wraps(func)
635640
def inner(*args, **kwds):
636641
try:
@@ -840,7 +845,7 @@ def _next_in_mro(cls):
840845
# Look for the last occurrence of Generic or Generic[...].
841846
for i, c in enumerate(cls.__mro__[:-1]):
842847
if isinstance(c, GenericMeta) and _gorg(c) is Generic:
843-
next_in_mro = cls.__mro__[i+1]
848+
next_in_mro = cls.__mro__[i + 1]
844849
return next_in_mro
845850

846851

@@ -849,8 +854,10 @@ def _valid_for_check(cls):
849854
if cls is Generic:
850855
raise TypeError("Class %r cannot be used with class "
851856
"or instance checks" % cls)
852-
if (cls.__origin__ is not None and
853-
sys._getframe(3).f_globals['__name__'] not in ['abc', 'functools']):
857+
if (
858+
cls.__origin__ is not None and
859+
sys._getframe(3).f_globals['__name__'] not in ['abc', 'functools']
860+
):
854861
raise TypeError("Parameterized generics cannot be used with class "
855862
"or instance checks")
856863

@@ -986,9 +993,12 @@ def __new__(cls, name, bases, namespace,
986993
# This allows unparameterized generic collections to be used
987994
# with issubclass() and isinstance() in the same way as their
988995
# collections.abc counterparts (e.g., isinstance([], Iterable)).
989-
if ('__subclasshook__' not in namespace and extra # allow overriding
990-
or hasattr(self.__subclasshook__, '__name__') and
991-
self.__subclasshook__.__name__ == '__extrahook__'):
996+
if (
997+
# allow overriding
998+
'__subclasshook__' not in namespace and extra or
999+
hasattr(self.__subclasshook__, '__name__') and
1000+
self.__subclasshook__.__name__ == '__extrahook__'
1001+
):
9921002
self.__subclasshook__ = _make_subclasshook(self)
9931003
if isinstance(extra, abc.ABCMeta):
9941004
self._abc_registry = extra._abc_registry
@@ -1192,13 +1202,13 @@ def __getitem__(self, parameters):
11921202
return super().__getitem__(parameters)
11931203

11941204
def __instancecheck__(self, obj):
1195-
if self.__args__ == None:
1205+
if self.__args__ is None:
11961206
return isinstance(obj, tuple)
11971207
raise TypeError("Parameterized Tuple cannot be used "
11981208
"with isinstance().")
11991209

12001210
def __subclasscheck__(self, cls):
1201-
if self.__args__ == None:
1211+
if self.__args__ is None:
12021212
return issubclass(cls, tuple)
12031213
raise TypeError("Parameterized Tuple cannot be used "
12041214
"with issubclass().")
@@ -1252,7 +1262,7 @@ def __getitem__(self, parameters):
12521262
with hashable arguments to improve speed.
12531263
"""
12541264

1255-
if self.__origin__ is not None or not _geqv(self, Callable):
1265+
if self.__origin__ is not None or not _geqv(self, Callable):
12561266
return super().__getitem__(parameters)
12571267
if not isinstance(parameters, tuple) or len(parameters) != 2:
12581268
raise TypeError("Callable must be used as "
@@ -1280,7 +1290,7 @@ def __getitem_inner__(self, parameters):
12801290
return super().__getitem__(parameters)
12811291

12821292

1283-
class Callable(extra=collections_abc.Callable, metaclass = CallableMeta):
1293+
class Callable(extra=collections_abc.Callable, metaclass=CallableMeta):
12841294
"""Callable type; Callable[[int], str] is a function of (int) -> str.
12851295
12861296
The subscription syntax must always be used with exactly two
@@ -1442,10 +1452,12 @@ def get_type_hints(obj, globalns=None, localns=None):
14421452
hints = getattr(obj, '__annotations__', None)
14431453
if hints is None:
14441454
# Return empty annotations for something that _could_ have them.
1445-
if (isinstance(obj, types.FunctionType) or
1455+
if (
1456+
isinstance(obj, types.FunctionType) or
14461457
isinstance(obj, types.BuiltinFunctionType) or
14471458
isinstance(obj, types.MethodType) or
1448-
isinstance(obj, types.ModuleType)):
1459+
isinstance(obj, types.ModuleType)
1460+
):
14491461
return {}
14501462
else:
14511463
raise TypeError('{!r} is not a module, class, method, '
@@ -1485,7 +1497,7 @@ def no_type_check(arg):
14851497
no_type_check(obj)
14861498
try:
14871499
arg.__no_type_check__ = True
1488-
except TypeError: # built-in classes
1500+
except TypeError: # built-in classes
14891501
pass
14901502
return arg
14911503

@@ -1771,14 +1783,15 @@ class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co],
17711783
class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping):
17721784
__slots__ = ()
17731785

1786+
17741787
if hasattr(collections_abc, 'Reversible'):
17751788
if hasattr(collections_abc, 'Collection'):
17761789
class Sequence(Reversible[T_co], Collection[T_co],
1777-
extra=collections_abc.Sequence):
1790+
extra=collections_abc.Sequence):
17781791
__slots__ = ()
17791792
else:
17801793
class Sequence(Sized, Reversible[T_co], Container[T_co],
1781-
extra=collections_abc.Sequence):
1794+
extra=collections_abc.Sequence):
17821795
__slots__ = ()
17831796
else:
17841797
class Sequence(Sized, Iterable[T_co], Container[T_co],
@@ -1804,6 +1817,7 @@ def __new__(cls, *args, **kwds):
18041817
"use list() instead")
18051818
return _generic_new(list, cls, *args, **kwds)
18061819

1820+
18071821
class Deque(collections.deque, MutableSequence[T], extra=collections.deque):
18081822

18091823
__slots__ = ()
@@ -1814,6 +1828,7 @@ def __new__(cls, *args, **kwds):
18141828
"use deque() instead")
18151829
return _generic_new(collections.deque, cls, *args, **kwds)
18161830

1831+
18171832
class Set(set, MutableSet[T], extra=set):
18181833

18191834
__slots__ = ()
@@ -1871,6 +1886,7 @@ def __new__(cls, *args, **kwds):
18711886
"use dict() instead")
18721887
return _generic_new(dict, cls, *args, **kwds)
18731888

1889+
18741890
class DefaultDict(collections.defaultdict, MutableMapping[KT, VT],
18751891
extra=collections.defaultdict):
18761892

@@ -1882,6 +1898,7 @@ def __new__(cls, *args, **kwds):
18821898
"use collections.defaultdict() instead")
18831899
return _generic_new(collections.defaultdict, cls, *args, **kwds)
18841900

1901+
18851902
# Determine what base class to use for Generator.
18861903
if hasattr(collections_abc, 'Generator'):
18871904
# Sufficiently recent versions of 3.5 have a Generator ABC.
@@ -1901,6 +1918,7 @@ def __new__(cls, *args, **kwds):
19011918
"create a subclass instead")
19021919
return _generic_new(_G_base, cls, *args, **kwds)
19031920

1921+
19041922
if hasattr(collections_abc, 'AsyncGenerator'):
19051923
class AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra],
19061924
extra=collections_abc.AsyncGenerator):
@@ -1976,14 +1994,15 @@ def __new__(cls, typename, bases, ns):
19761994
defaults.append(default_value)
19771995
defaults_dict[field_name] = default_value
19781996
elif defaults:
1979-
raise TypeError("Non-default namedtuple field {field_name} cannot follow default"
1980-
" field(s) {default_names}"
1997+
raise TypeError("Non-default namedtuple field {field_name} cannot "
1998+
"follow default field(s) {default_names}"
19811999
.format(field_name=field_name,
19822000
default_names=', '.join(defaults_dict.keys())))
19832001
nm_tpl.__new__.__defaults__ = tuple(defaults)
19842002
nm_tpl._field_defaults = defaults_dict
19852003
return nm_tpl
19862004

2005+
19872006
class NamedTuple(metaclass=NamedTupleMeta):
19882007
"""Typed version of namedtuple.
19892008
@@ -2207,6 +2226,7 @@ class io:
22072226
TextIO = TextIO
22082227
BinaryIO = BinaryIO
22092228

2229+
22102230
io.__name__ = __name__ + '.io'
22112231
sys.modules[io.__name__] = io
22122232

@@ -2224,5 +2244,6 @@ class re:
22242244
Pattern = Pattern
22252245
Match = Match
22262246

2247+
22272248
re.__name__ = __name__ + '.re'
22282249
sys.modules[re.__name__] = re

0 commit comments

Comments
 (0)