Skip to content

Commit 67d3b42

Browse files
ilevkivskyigvanrossum
authored andcommitted
Improve docstrings and error messages (#331)
1 parent 1881ffd commit 67d3b42

File tree

2 files changed

+85
-76
lines changed

2 files changed

+85
-76
lines changed

python2/typing.py

Lines changed: 41 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -91,10 +91,11 @@ def _trim_name(nm):
9191

9292

9393
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).
9596
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().
9899
"""
99100

100101
_is_protocol = False
@@ -115,8 +116,8 @@ def __init__(self, *args, **kwds):
115116
def _eval_type(self, globalns, localns):
116117
"""Override this in subclasses to interpret forward references.
117118
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],
120121
where C is an object found in globalns or localns (searching
121122
localns first, of course).
122123
"""
@@ -131,7 +132,7 @@ def __repr__(self):
131132

132133

133134
class _TypingBase(object):
134-
"""Indicator of special typing constructs."""
135+
"""Internal indicator of special typing constructs."""
135136
__metaclass__ = TypingMeta
136137
__slots__ = ()
137138

@@ -168,10 +169,10 @@ def __call__(self, *args, **kwds):
168169

169170

170171
class _FinalTypingBase(_TypingBase):
171-
"""Mix-in class to prevent instantiation.
172+
"""Internal mix-in class to prevent instantiation.
172173
173174
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.
175176
"""
176177

177178
__slots__ = ()
@@ -187,19 +188,19 @@ def __reduce__(self):
187188

188189

189190
class _ForwardRef(_TypingBase):
190-
"""Wrapper to hold a forward reference."""
191+
"""Internal wrapper to hold a forward reference."""
191192

192193
__slots__ = ('__forward_arg__', '__forward_code__',
193194
'__forward_evaluated__', '__forward_value__')
194195

195196
def __init__(self, arg):
196197
super(_ForwardRef, self).__init__(arg)
197198
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,))
199200
try:
200201
code = compile(arg, '<string>', 'eval')
201202
except SyntaxError:
202-
raise SyntaxError('ForwardRef must be an expression -- got %r' %
203+
raise SyntaxError('Forward reference must be an expression -- got %r' %
203204
(arg,))
204205
self.__forward_arg__ = arg
205206
self.__forward_code__ = code
@@ -309,7 +310,7 @@ def _eval_type(t, globalns, localns):
309310

310311

311312
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).
313314
314315
As a special case, accept None and return type(None) instead.
315316
Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable.
@@ -336,7 +337,7 @@ def _type_check(arg, msg):
336337

337338

338339
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).
340341
341342
If obj is a type, we return a shorter version than the default
342343
type.__repr__, based on the module and qualified name, which is
@@ -470,7 +471,7 @@ class TypeVar(_TypingBase):
470471
as for generic function definitions. See class Generic for more
471472
information on generic types. Generic functions work as follows:
472473
473-
def repeat(x: T, n: int) -> Sequence[T]:
474+
def repeat(x: T, n: int) -> List[T]:
474475
'''Return a list containing n references to x.'''
475476
return [x]*n
476477
@@ -483,10 +484,7 @@ def longest(x: A, y: A) -> A:
483484
that if the arguments are instances of some subclass of str,
484485
the return type is still plain str.
485486
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.
490488
491489
Type variables defined with covariant=True or contravariant=True
492490
can be used do declare covariant or contravariant generic types.
@@ -563,7 +561,7 @@ def __subclasscheck__(self, cls):
563561

564562

565563
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
567565
found in tvars with corresponding substitution from args or
568566
with corresponding substitution sub-tree if arg is a generic type.
569567
"""
@@ -580,9 +578,15 @@ def _replace_arg(arg, tvars, args):
580578

581579

582580
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)]
586590
"""
587591

588592
if cls.__origin__ is None:
@@ -607,7 +611,7 @@ def _subs_tree(cls, tvars=None, args=None):
607611

608612

609613
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
611615
among parameters, then remove duplicates and strict subclasses.
612616
"""
613617

@@ -648,7 +652,7 @@ def _remove_dups_flatten(parameters):
648652

649653

650654
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).
652656
if not cls.__parameters__:
653657
raise TypeError("%s is not a generic class" % repr(cls))
654658
alen = len(parameters)
@@ -867,18 +871,18 @@ def __getitem__(self, arg):
867871

868872

869873
def _gorg(a):
870-
"""Return the farthest origin of a generic class."""
874+
"""Return the farthest origin of a generic class (internal helper)."""
871875
assert isinstance(a, GenericMeta)
872876
while a.__origin__ is not None:
873877
a = a.__origin__
874878
return a
875879

876880

877881
def _geqv(a, b):
878-
"""Return whether two generic classes are equivalent.
882+
"""Return whether two generic classes are equivalent (internal helper).
879883
880884
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.
882886
883887
However, X is not equivalent to a subclass of X.
884888
@@ -904,6 +908,7 @@ def _next_in_mro(cls):
904908

905909

906910
def _valid_for_check(cls):
911+
"""An internal helper to prohibit isinstance([1], List[str]) etc."""
907912
if cls is Generic:
908913
raise TypeError("Class %r cannot be used with class "
909914
"or instance checks" % cls)
@@ -1169,8 +1174,8 @@ def _generic_new(base_cls, cls, *args, **kwds):
11691174
class Generic(object):
11701175
"""Abstract base class for generic types.
11711176
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.
11741179
For example, a generic mapping type might be defined as::
11751180
11761181
class Mapping(Generic[KT, VT]):
@@ -1198,18 +1203,18 @@ def __new__(cls, *args, **kwds):
11981203

11991204

12001205
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
12031208
to sneak in where prohibited.
12041209
"""
12051210

12061211

12071212
class _TypingEllipsis(object):
1208-
"""Ditto for ..."""
1213+
"""Internal placeholder for ... (ellipsis)."""
12091214

12101215

12111216
class TupleMeta(GenericMeta):
1212-
"""Metaclass for Tuple"""
1217+
"""Metaclass for Tuple (internal)."""
12131218

12141219
@_tp_cache
12151220
def __getitem__(self, parameters):
@@ -1288,7 +1293,7 @@ def _tree_repr(self, tree):
12881293
'[[%s], %s]' % (', '.join(arg_list[:-1]), arg_list[-1]))
12891294

12901295
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
12921297
with hashable arguments to improve speed.
12931298
"""
12941299

@@ -1325,7 +1330,7 @@ class Callable(object):
13251330
13261331
The subscription syntax must always be used with exactly two
13271332
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.
13291334
13301335
There is no syntax to indicate optional or keyword arguments,
13311336
such function types are rarely used as callback types.
@@ -1522,7 +1527,7 @@ def _get_protocol_attrs(self):
15221527
class _Protocol(object):
15231528
"""Internal base class for protocol classes.
15241529
1525-
This implements a simple-minded structural isinstance check
1530+
This implements a simple-minded structural issubclass check
15261531
(similar but more general than the one-offs in collections.abc
15271532
such as Hashable).
15281533
"""

0 commit comments

Comments
 (0)