@@ -91,10 +91,11 @@ def _trim_name(nm):
91
91
92
92
93
93
class TypingMeta (type ):
94
- """Metaclass for every type defined below.
94
+ """Metaclass for most types defined in typing module
95
+ (not a part of public API).
95
96
96
- This also defines a dummy constructor (all the work is done in
97
- __new__) and a nicer repr().
97
+ This also defines a dummy constructor (all the work for most typing
98
+ constructs is done in __new__) and a nicer repr().
98
99
"""
99
100
100
101
_is_protocol = False
@@ -115,8 +116,8 @@ def __init__(self, *args, **kwds):
115
116
def _eval_type (self , globalns , localns ):
116
117
"""Override this in subclasses to interpret forward references.
117
118
118
- For example, Union ['C'] is internally stored as
119
- Union [_ForwardRef('C')], which should evaluate to _Union [C],
119
+ For example, List ['C'] is internally stored as
120
+ List [_ForwardRef('C')], which should evaluate to List [C],
120
121
where C is an object found in globalns or localns (searching
121
122
localns first, of course).
122
123
"""
@@ -131,7 +132,7 @@ def __repr__(self):
131
132
132
133
133
134
class _TypingBase (object ):
134
- """Indicator of special typing constructs."""
135
+ """Internal indicator of special typing constructs."""
135
136
__metaclass__ = TypingMeta
136
137
__slots__ = ()
137
138
@@ -168,10 +169,10 @@ def __call__(self, *args, **kwds):
168
169
169
170
170
171
class _FinalTypingBase (_TypingBase ):
171
- """Mix -in class to prevent instantiation.
172
+ """Internal mix -in class to prevent instantiation.
172
173
173
174
Prevents instantiation unless _root=True is given in class call.
174
- It is used to create pseudo-singleton instances Any, Union, Tuple , etc.
175
+ It is used to create pseudo-singleton instances Any, Union, Optional , etc.
175
176
"""
176
177
177
178
__slots__ = ()
@@ -187,19 +188,19 @@ def __reduce__(self):
187
188
188
189
189
190
class _ForwardRef (_TypingBase ):
190
- """Wrapper to hold a forward reference."""
191
+ """Internal wrapper to hold a forward reference."""
191
192
192
193
__slots__ = ('__forward_arg__' , '__forward_code__' ,
193
194
'__forward_evaluated__' , '__forward_value__' )
194
195
195
196
def __init__ (self , arg ):
196
197
super (_ForwardRef , self ).__init__ (arg )
197
198
if not isinstance (arg , basestring ):
198
- raise TypeError ('ForwardRef must be a string -- got %r' % (arg ,))
199
+ raise TypeError ('Forward reference must be a string -- got %r' % (arg ,))
199
200
try :
200
201
code = compile (arg , '<string>' , 'eval' )
201
202
except SyntaxError :
202
- raise SyntaxError ('ForwardRef must be an expression -- got %r' %
203
+ raise SyntaxError ('Forward reference must be an expression -- got %r' %
203
204
(arg ,))
204
205
self .__forward_arg__ = arg
205
206
self .__forward_code__ = code
@@ -309,7 +310,7 @@ def _eval_type(t, globalns, localns):
309
310
310
311
311
312
def _type_check (arg , msg ):
312
- """Check that the argument is a type, and return it.
313
+ """Check that the argument is a type, and return it (internal helper) .
313
314
314
315
As a special case, accept None and return type(None) instead.
315
316
Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable.
@@ -336,7 +337,7 @@ def _type_check(arg, msg):
336
337
337
338
338
339
def _type_repr (obj ):
339
- """Return the repr() of an object, special-casing types.
340
+ """Return the repr() of an object, special-casing types (internal helper) .
340
341
341
342
If obj is a type, we return a shorter version than the default
342
343
type.__repr__, based on the module and qualified name, which is
@@ -470,7 +471,7 @@ class TypeVar(_TypingBase):
470
471
as for generic function definitions. See class Generic for more
471
472
information on generic types. Generic functions work as follows:
472
473
473
- def repeat(x: T, n: int) -> Sequence [T]:
474
+ def repeat(x: T, n: int) -> List [T]:
474
475
'''Return a list containing n references to x.'''
475
476
return [x]*n
476
477
@@ -483,10 +484,7 @@ def longest(x: A, y: A) -> A:
483
484
that if the arguments are instances of some subclass of str,
484
485
the return type is still plain str.
485
486
486
- At runtime, isinstance(x, T) will raise TypeError. However,
487
- issubclass(C, T) is true for any class C, and issubclass(str, A)
488
- and issubclass(bytes, A) are true, and issubclass(int, A) is
489
- false. (TODO: Why is this needed? This may change. See #136.)
487
+ At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
490
488
491
489
Type variables defined with covariant=True or contravariant=True
492
490
can be used do declare covariant or contravariant generic types.
@@ -563,7 +561,7 @@ def __subclasscheck__(self, cls):
563
561
564
562
565
563
def _replace_arg (arg , tvars , args ):
566
- """ A helper fuunction : replace arg if it is a type variable
564
+ """An internal helper function : replace arg if it is a type variable
567
565
found in tvars with corresponding substitution from args or
568
566
with corresponding substitution sub-tree if arg is a generic type.
569
567
"""
@@ -580,9 +578,15 @@ def _replace_arg(arg, tvars, args):
580
578
581
579
582
580
def _subs_tree (cls , tvars = None , args = None ):
583
- """ Calculate substitution tree for generic cls after
584
- replacing its type parameters with substitutions in tvars -> args (if any).
585
- Repeat the same cyclicaly following __origin__'s.
581
+ """An internal helper function: calculate substitution tree
582
+ for generic cls after replacing its type parameters with
583
+ substitutions in tvars -> args (if any).
584
+ Repeat the same following __origin__'s.
585
+
586
+ Return a list of arguments with all possible substitutions
587
+ performed. Arguments that are generic classes themselves are represented
588
+ as tuples (so that no new classes are created by this function).
589
+ For example: _subs_tree(List[Tuple[int, T]][str]) == [(Tuple, int, str)]
586
590
"""
587
591
588
592
if cls .__origin__ is None :
@@ -607,7 +611,7 @@ def _subs_tree(cls, tvars=None, args=None):
607
611
608
612
609
613
def _remove_dups_flatten (parameters ):
610
- """ A helper for Union creation and substitution: flatten Union's
614
+ """An internal helper for Union creation and substitution: flatten Union's
611
615
among parameters, then remove duplicates and strict subclasses.
612
616
"""
613
617
@@ -648,7 +652,7 @@ def _remove_dups_flatten(parameters):
648
652
649
653
650
654
def _check_generic (cls , parameters ):
651
- # Check correct count for parameters of a generic cls.
655
+ # Check correct count for parameters of a generic cls (internal helper) .
652
656
if not cls .__parameters__ :
653
657
raise TypeError ("%s is not a generic class" % repr (cls ))
654
658
alen = len (parameters )
@@ -867,18 +871,18 @@ def __getitem__(self, arg):
867
871
868
872
869
873
def _gorg (a ):
870
- """Return the farthest origin of a generic class."""
874
+ """Return the farthest origin of a generic class (internal helper) ."""
871
875
assert isinstance (a , GenericMeta )
872
876
while a .__origin__ is not None :
873
877
a = a .__origin__
874
878
return a
875
879
876
880
877
881
def _geqv (a , b ):
878
- """Return whether two generic classes are equivalent.
882
+ """Return whether two generic classes are equivalent (internal helper) .
879
883
880
884
The intention is to consider generic class X and any of its
881
- parameterized forms (X[T], X[int], etc.) as equivalent.
885
+ parameterized forms (X[T], X[int], etc.) as equivalent.
882
886
883
887
However, X is not equivalent to a subclass of X.
884
888
@@ -904,6 +908,7 @@ def _next_in_mro(cls):
904
908
905
909
906
910
def _valid_for_check (cls ):
911
+ """An internal helper to prohibit isinstance([1], List[str]) etc."""
907
912
if cls is Generic :
908
913
raise TypeError ("Class %r cannot be used with class "
909
914
"or instance checks" % cls )
@@ -1169,8 +1174,8 @@ def _generic_new(base_cls, cls, *args, **kwds):
1169
1174
class Generic (object ):
1170
1175
"""Abstract base class for generic types.
1171
1176
1172
- A generic type is typically declared by inheriting from an
1173
- instantiation of this class with one or more type variables.
1177
+ A generic type is typically declared by inheriting from
1178
+ this class parameterized with one or more type variables.
1174
1179
For example, a generic mapping type might be defined as::
1175
1180
1176
1181
class Mapping(Generic[KT, VT]):
@@ -1198,18 +1203,18 @@ def __new__(cls, *args, **kwds):
1198
1203
1199
1204
1200
1205
class _TypingEmpty (object ):
1201
- """Placeholder for () or []. Used by TupleMeta and CallableMeta
1202
- to allow empy list/tuple in specific places, without allowing them
1206
+ """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
1207
+ to allow empty list/tuple in specific places, without allowing them
1203
1208
to sneak in where prohibited.
1204
1209
"""
1205
1210
1206
1211
1207
1212
class _TypingEllipsis (object ):
1208
- """Ditto for ..."""
1213
+ """Internal placeholder for ... (ellipsis) ."""
1209
1214
1210
1215
1211
1216
class TupleMeta (GenericMeta ):
1212
- """Metaclass for Tuple"""
1217
+ """Metaclass for Tuple (internal). """
1213
1218
1214
1219
@_tp_cache
1215
1220
def __getitem__ (self , parameters ):
@@ -1288,7 +1293,7 @@ def _tree_repr(self, tree):
1288
1293
'[[%s], %s]' % (', ' .join (arg_list [:- 1 ]), arg_list [- 1 ]))
1289
1294
1290
1295
def __getitem__ (self , parameters ):
1291
- """ A thin wrapper around __getitem_inner__ to provide the latter
1296
+ """A thin wrapper around __getitem_inner__ to provide the latter
1292
1297
with hashable arguments to improve speed.
1293
1298
"""
1294
1299
@@ -1325,7 +1330,7 @@ class Callable(object):
1325
1330
1326
1331
The subscription syntax must always be used with exactly two
1327
1332
values: the argument list and the return type. The argument list
1328
- must be a list of types; the return type must be a single type.
1333
+ must be a list of types or ellipsis ; the return type must be a single type.
1329
1334
1330
1335
There is no syntax to indicate optional or keyword arguments,
1331
1336
such function types are rarely used as callback types.
@@ -1522,7 +1527,7 @@ def _get_protocol_attrs(self):
1522
1527
class _Protocol (object ):
1523
1528
"""Internal base class for protocol classes.
1524
1529
1525
- This implements a simple-minded structural isinstance check
1530
+ This implements a simple-minded structural issubclass check
1526
1531
(similar but more general than the one-offs in collections.abc
1527
1532
such as Hashable).
1528
1533
"""
0 commit comments