Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b24569a

Browse files
committed
Issue #28556: upstream improvements to docstrings and error messages by Ivan Levkivskyi (#331)
1 parent 6e723d2 commit b24569a

1 file changed

Lines changed: 44 additions & 40 deletions

File tree

Lib/typing.py

Lines changed: 44 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -100,16 +100,16 @@ def _trim_name(nm):
100100

101101

102102
class TypingMeta(type):
103-
"""Metaclass for every type defined below.
103+
"""Metaclass for most types defined in typing module
104+
(not a part of public API).
104105
105106
This overrides __new__() to require an extra keyword parameter
106107
'_root', which serves as a guard against naive subclassing of the
107108
typing classes. Any legitimate class defined using a metaclass
108-
derived from TypingMeta (including internal subclasses created by
109-
e.g. Union[X, Y]) must pass _root=True.
109+
derived from TypingMeta must pass _root=True.
110110
111-
This also defines a dummy constructor (all the work is done in
112-
__new__) and a nicer repr().
111+
This also defines a dummy constructor (all the work for most typing
112+
constructs is done in __new__) and a nicer repr().
113113
"""
114114

115115
_is_protocol = False
@@ -126,8 +126,8 @@ def __init__(self, *args, **kwds):
126126
def _eval_type(self, globalns, localns):
127127
"""Override this in subclasses to interpret forward references.
128128
129-
For example, Union['C'] is internally stored as
130-
Union[_ForwardRef('C')], which should evaluate to _Union[C],
129+
For example, List['C'] is internally stored as
130+
List[_ForwardRef('C')], which should evaluate to List[C],
131131
where C is an object found in globalns or localns (searching
132132
localns first, of course).
133133
"""
@@ -142,7 +142,7 @@ def __repr__(self):
142142

143143

144144
class _TypingBase(metaclass=TypingMeta, _root=True):
145-
"""Indicator of special typing constructs."""
145+
"""Internal indicator of special typing constructs."""
146146

147147
__slots__ = ()
148148

@@ -179,10 +179,10 @@ def __call__(self, *args, **kwds):
179179

180180

181181
class _FinalTypingBase(_TypingBase, _root=True):
182-
"""Mix-in class to prevent instantiation.
182+
"""Internal mix-in class to prevent instantiation.
183183
184184
Prevents instantiation unless _root=True is given in class call.
185-
It is used to create pseudo-singleton instances Any, Union, Tuple, etc.
185+
It is used to create pseudo-singleton instances Any, Union, Optional, etc.
186186
"""
187187

188188
__slots__ = ()
@@ -198,19 +198,19 @@ def __reduce__(self):
198198

199199

200200
class _ForwardRef(_TypingBase, _root=True):
201-
"""Wrapper to hold a forward reference."""
201+
"""Internal wrapper to hold a forward reference."""
202202

203203
__slots__ = ('__forward_arg__', '__forward_code__',
204204
'__forward_evaluated__', '__forward_value__')
205205

206206
def __init__(self, arg):
207207
super().__init__(arg)
208208
if not isinstance(arg, str):
209-
raise TypeError('ForwardRef must be a string -- got %r' % (arg,))
209+
raise TypeError('Forward reference must be a string -- got %r' % (arg,))
210210
try:
211211
code = compile(arg, '<string>', 'eval')
212212
except SyntaxError:
213-
raise SyntaxError('ForwardRef must be an expression -- got %r' %
213+
raise SyntaxError('Forward reference must be an expression -- got %r' %
214214
(arg,))
215215
self.__forward_arg__ = arg
216216
self.__forward_code__ = code
@@ -336,7 +336,7 @@ def _eval_type(t, globalns, localns):
336336

337337

338338
def _type_check(arg, msg):
339-
"""Check that the argument is a type, and return it.
339+
"""Check that the argument is a type, and return it (internal helper).
340340
341341
As a special case, accept None and return type(None) instead.
342342
Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable.
@@ -363,7 +363,7 @@ def _type_check(arg, msg):
363363

364364

365365
def _type_repr(obj):
366-
"""Return the repr() of an object, special-casing types.
366+
"""Return the repr() of an object, special-casing types (internal helper).
367367
368368
If obj is a type, we return a shorter version than the default
369369
type.__repr__, based on the module and qualified name, which is
@@ -418,7 +418,7 @@ class TypeVar(_TypingBase, _root=True):
418418
as for generic function definitions. See class Generic for more
419419
information on generic types. Generic functions work as follows:
420420
421-
def repeat(x: T, n: int) -> Sequence[T]:
421+
def repeat(x: T, n: int) -> List[T]:
422422
'''Return a list containing n references to x.'''
423423
return [x]*n
424424
@@ -431,10 +431,7 @@ def longest(x: A, y: A) -> A:
431431
that if the arguments are instances of some subclass of str,
432432
the return type is still plain str.
433433
434-
At runtime, isinstance(x, T) will raise TypeError. However,
435-
issubclass(C, T) is true for any class C, and issubclass(str, A)
436-
and issubclass(bytes, A) are true, and issubclass(int, A) is
437-
false. (TODO: Why is this needed? This may change. See #136.)
434+
At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
438435
439436
Type variables defined with covariant=True or contravariant=True
440437
can be used do declare covariant or contravariant generic types.
@@ -509,7 +506,7 @@ def __subclasscheck__(self, cls):
509506

510507

511508
def _replace_arg(arg, tvars, args):
512-
""" A helper fuunction: replace arg if it is a type variable
509+
"""An internal helper function: replace arg if it is a type variable
513510
found in tvars with corresponding substitution from args or
514511
with corresponding substitution sub-tree if arg is a generic type.
515512
"""
@@ -526,9 +523,15 @@ def _replace_arg(arg, tvars, args):
526523

527524

528525
def _subs_tree(cls, tvars=None, args=None):
529-
""" Calculate substitution tree for generic cls after
530-
replacing its type parameters with substitutions in tvars -> args (if any).
531-
Repeat the same cyclicaly following __origin__'s.
526+
"""An internal helper function: calculate substitution tree
527+
for generic cls after replacing its type parameters with
528+
substitutions in tvars -> args (if any).
529+
Repeat the same following __origin__'s.
530+
531+
Return a list of arguments with all possible substitutions
532+
performed. Arguments that are generic classes themselves are represented
533+
as tuples (so that no new classes are created by this function).
534+
For example: _subs_tree(List[Tuple[int, T]][str]) == [(Tuple, int, str)]
532535
"""
533536

534537
if cls.__origin__ is None:
@@ -553,7 +556,7 @@ def _subs_tree(cls, tvars=None, args=None):
553556

554557

555558
def _remove_dups_flatten(parameters):
556-
""" A helper for Union creation and substitution: flatten Union's
559+
"""An internal helper for Union creation and substitution: flatten Union's
557560
among parameters, then remove duplicates and strict subclasses.
558561
"""
559562

@@ -594,7 +597,7 @@ def _remove_dups_flatten(parameters):
594597

595598

596599
def _check_generic(cls, parameters):
597-
# Check correct count for parameters of a generic cls.
600+
# Check correct count for parameters of a generic cls (internal helper).
598601
if not cls.__parameters__:
599602
raise TypeError("%s is not a generic class" % repr(cls))
600603
alen = len(parameters)
@@ -608,7 +611,7 @@ def _check_generic(cls, parameters):
608611

609612

610613
def _tp_cache(func):
611-
""" Caching for __getitem__ of generic types with a fallback to
614+
"""Internal wrapper caching __getitem__ of generic types with a fallback to
612615
original function for non-hashable arguments.
613616
"""
614617

@@ -788,18 +791,18 @@ def __getitem__(self, arg):
788791

789792

790793
def _gorg(a):
791-
"""Return the farthest origin of a generic class."""
794+
"""Return the farthest origin of a generic class (internal helper)."""
792795
assert isinstance(a, GenericMeta)
793796
while a.__origin__ is not None:
794797
a = a.__origin__
795798
return a
796799

797800

798801
def _geqv(a, b):
799-
"""Return whether two generic classes are equivalent.
802+
"""Return whether two generic classes are equivalent (internal helper).
800803
801804
The intention is to consider generic class X and any of its
802-
parameterized forms (X[T], X[int], etc.) as equivalent.
805+
parameterized forms (X[T], X[int], etc.) as equivalent.
803806
804807
However, X is not equivalent to a subclass of X.
805808
@@ -825,6 +828,7 @@ def _next_in_mro(cls):
825828

826829

827830
def _valid_for_check(cls):
831+
"""An internal helper to prohibit isinstance([1], List[str]) etc."""
828832
if cls is Generic:
829833
raise TypeError("Class %r cannot be used with class "
830834
"or instance checks" % cls)
@@ -1083,8 +1087,8 @@ def _generic_new(base_cls, cls, *args, **kwds):
10831087
class Generic(metaclass=GenericMeta):
10841088
"""Abstract base class for generic types.
10851089
1086-
A generic type is typically declared by inheriting from an
1087-
instantiation of this class with one or more type variables.
1090+
A generic type is typically declared by inheriting from
1091+
this class parameterized with one or more type variables.
10881092
For example, a generic mapping type might be defined as::
10891093
10901094
class Mapping(Generic[KT, VT]):
@@ -1111,18 +1115,18 @@ def __new__(cls, *args, **kwds):
11111115

11121116

11131117
class _TypingEmpty:
1114-
"""Placeholder for () or []. Used by TupleMeta and CallableMeta
1115-
to allow empy list/tuple in specific places, without allowing them
1118+
"""Internal placeholder for () or []. Used by TupleMeta and CallableMeta
1119+
to allow empty list/tuple in specific places, without allowing them
11161120
to sneak in where prohibited.
11171121
"""
11181122

11191123

11201124
class _TypingEllipsis:
1121-
"""Ditto for ..."""
1125+
"""Internal placeholder for ... (ellipsis)."""
11221126

11231127

11241128
class TupleMeta(GenericMeta):
1125-
"""Metaclass for Tuple"""
1129+
"""Metaclass for Tuple (internal)."""
11261130

11271131
@_tp_cache
11281132
def __getitem__(self, parameters):
@@ -1175,7 +1179,7 @@ def __new__(cls, *args, **kwds):
11751179

11761180

11771181
class CallableMeta(GenericMeta):
1178-
""" Metaclass for Callable."""
1182+
"""Metaclass for Callable (internal)."""
11791183

11801184
def __repr__(self):
11811185
if self.__origin__ is None:
@@ -1199,7 +1203,7 @@ def _tree_repr(self, tree):
11991203
'[[%s], %s]' % (', '.join(arg_list[:-1]), arg_list[-1]))
12001204

12011205
def __getitem__(self, parameters):
1202-
""" A thin wrapper around __getitem_inner__ to provide the latter
1206+
"""A thin wrapper around __getitem_inner__ to provide the latter
12031207
with hashable arguments to improve speed.
12041208
"""
12051209

@@ -1236,7 +1240,7 @@ class Callable(extra=collections_abc.Callable, metaclass = CallableMeta):
12361240
12371241
The subscription syntax must always be used with exactly two
12381242
values: the argument list and the return type. The argument list
1239-
must be a list of types; the return type must be a single type.
1243+
must be a list of types or ellipsis; the return type must be a single type.
12401244
12411245
There is no syntax to indicate optional or keyword arguments,
12421246
such function types are rarely used as callback types.
@@ -1565,7 +1569,7 @@ def _get_protocol_attrs(self):
15651569
class _Protocol(metaclass=_ProtocolMeta):
15661570
"""Internal base class for protocol classes.
15671571
1568-
This implements a simple-minded structural isinstance check
1572+
This implements a simple-minded structural issubclass check
15691573
(similar but more general than the one-offs in collections.abc
15701574
such as Hashable).
15711575
"""

0 commit comments

Comments
 (0)