Skip to content

Commit 5c6bac6

Browse files
committed
Merge pull request #1 from ambv/master
Update with master
2 parents 177beb2 + 35480d2 commit 5c6bac6

File tree

3 files changed

+70
-18
lines changed

3 files changed

+70
-18
lines changed

pep-0484.txt

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ Status: Accepted
99
Type: Standards Track
1010
Content-Type: text/x-rst
1111
Created: 29-Sep-2014
12+
Python-Version: 3.5
1213
Post-History: 16-Jan-2015,20-Mar-2015,17-Apr-2015,20-May-2015,22-May-2015
1314
Resolution: https://mail.python.org/pipermail/python-dev/2015-May/140104.html
1415

@@ -85,7 +86,7 @@ Non-goals
8586
---------
8687

8788
While the proposed typing module will contain some building blocks for
88-
runtime type checking -- in particular the `get_type_hints()`
89+
runtime type checking -- in particular the ``get_type_hints()``
8990
function -- third party packages would have to be developed to
9091
implement specific runtime type checking functionality, for example
9192
using decorators or metaclasses. Using type hints for performance
@@ -262,10 +263,10 @@ arguments with ``Callable``. Similarly, there is no support for
262263
specifying callback signatures with a variable number of argument of a
263264
specific type.
264265

265-
Because `typing.Callable` does double-duty as a replacement for
266-
`collections.abc.Callable`, `isinstance(x, typing.Callable)` is
267-
implemented by deferring to `isinstance(x, collections.abc.Callable)`.
268-
However, `isinstance(x, typing.Callable[...])` is not supported.
266+
Because ``typing.Callable`` does double-duty as a replacement for
267+
``collections.abc.Callable``, ``isinstance(x, typing.Callable)`` is
268+
implemented by deferring to ```isinstance(x, collections.abc.Callable)``.
269+
However, ``isinstance(x, typing.Callable[...])`` is not supported.
269270

270271

271272
Generics
@@ -413,7 +414,7 @@ You can use multiple inheritance with ``Generic``::
413414

414415
Subclassing a generic class without specifying type parameters assumes
415416
``Any`` for each position. In the following example, ``MyIterable``
416-
is not generic but implicitly inherits from ``Iterable[Any]``:
417+
is not generic but implicitly inherits from ``Iterable[Any]``::
417418

418419
from typing import Iterable
419420

@@ -441,20 +442,20 @@ Now there are two ways we can instantiate this class; the type
441442
inferred by a type checker may be different depending on the form we
442443
use. The first way is to give the value of the type parameter
443444
explicitly -- this overrides whatever type inference the type
444-
checker would otherwise perform:
445+
checker would otherwise perform::
445446

446447
x = Node[T]() # The type inferred for x is Node[T].
447448

448449
y = Node[int]() # The type inferred for y is Node[int].
449450

450451
If no explicit types are given, the type checker is given some
451-
freedom. Consider this code:
452+
freedom. Consider this code::
452453

453454
x = Node()
454455

455456
The inferred type could be ``Node[Any]``, as there isn't enough
456457
context to infer a more precise type. Alternatively, a type checker
457-
may reject the line and require an explicit annotation, like this:
458+
may reject the line and require an explicit annotation, like this::
458459

459460
x = Node() # type: Node[int] # Inferred type is Node[int].
460461

@@ -943,7 +944,7 @@ ellipsis::
943944

944945
stream = ... # type: IO[str]
945946

946-
In non-stub code, there is a similar special case:
947+
In non-stub code, there is a similar special case::
947948

948949
from typing import IO
949950

@@ -986,7 +987,7 @@ than a type checker may be able to infer. For example::
986987
return cast(str, a[index])
987988

988989
Some type checkers may not be able to infer that the type of
989-
``a[index]`` is ``str`` and only infer ``object`` or ``Any``", but we
990+
``a[index]`` is ``str`` and only infer ``object`` or ``Any``, but we
990991
know that (if the code gets to that point) it must be a string. The
991992
``cast(t, x)`` call tells the type checker that we are confident that
992993
the type of ``x`` is ``t``. At runtime a cast always returns the
@@ -1110,7 +1111,7 @@ calling ``overload()`` directly raises ``RuntimeError``.
11101111

11111112
A constrained ``TypeVar`` type can often be used instead of using the
11121113
``@overload`` decorator. For example, the definitions of ``concat1``
1113-
and ``concat2`` in this stub file are equivalent:
1114+
and ``concat2`` in this stub file are equivalent::
11141115

11151116
from typing import TypeVar
11161117

@@ -1133,7 +1134,7 @@ Another important difference between type variables such as ``AnyStr``
11331134
and using ``@overload`` is that the prior can also be used to define
11341135
constraints for generic class type parameters. For example, the type
11351136
parameter of the generic class ``typing.IO`` is constrained (only
1136-
``IO[str]``, ``IO[bytes]`` and ``IO[Any]`` are valid):
1137+
``IO[str]``, ``IO[bytes]`` and ``IO[Any]`` are valid)::
11371138

11381139
class IO(Generic[AnyStr]): ...
11391140

@@ -1645,7 +1646,7 @@ References
16451646
http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29
16461647

16471648
.. [typeshed]
1648-
https://github.com/JukkaL/typeshed/
1649+
https://github.com/python/typeshed/
16491650

16501651
.. [pyflakes]
16511652
https://github.com/pyflakes/pyflakes/

prototyping/test_typing.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,14 @@ def test_repr(self):
459459
ctv = Callable[..., str]
460460
self.assertEqual(repr(ctv), 'typing.Callable[..., str]')
461461

462+
def test_callable_with_ellipsis(self):
463+
464+
def foo(a: Callable[..., T]):
465+
pass
466+
467+
self.assertEqual(get_type_hints(foo, globals(), locals()),
468+
{'a': Callable[..., T]})
469+
462470

463471
XK = TypeVar('XK', str, bytes)
464472
XV = TypeVar('XV')
@@ -809,6 +817,14 @@ def foo(a: Callable[['T'], 'T']):
809817
self.assertEqual(get_type_hints(foo, globals(), locals()),
810818
{'a': Callable[[T], T]})
811819

820+
def test_callable_with_ellipsis_forward(self):
821+
822+
def foo(a: 'Callable[..., T]'):
823+
pass
824+
825+
self.assertEqual(get_type_hints(foo, globals(), locals()),
826+
{'a': Callable[..., T]})
827+
812828
def test_syntax_error(self):
813829

814830
with self.assertRaises(SyntaxError):

prototyping/typing.py

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,8 @@ def __repr__(self):
128128
class Final:
129129
"""Mix-in class to prevent instantiation."""
130130

131+
__slots__ = ()
132+
131133
def __new__(self, *args, **kwds):
132134
raise TypeError("Cannot instantiate %r" % self.__class__)
133135

@@ -204,6 +206,8 @@ class _TypeAlias:
204206
False.
205207
"""
206208

209+
__slots__ = ('name', 'type_var', 'impl_type', 'type_checker')
210+
207211
def __new__(cls, *args, **kwds):
208212
"""Constructor.
209213
@@ -341,6 +345,8 @@ class Any(Final, metaclass=AnyMeta, _root=True):
341345
- As a special case, Any and object are subclasses of each other.
342346
"""
343347

348+
__slots__ = ()
349+
344350

345351
class TypeVar(TypingMeta, metaclass=TypingMeta, _root=True):
346352
"""Type variable.
@@ -635,6 +641,8 @@ class Optional(Final, metaclass=OptionalMeta, _root=True):
635641
Optional[X] is equivalent to Union[X, type(None)].
636642
"""
637643

644+
__slots__ = ()
645+
638646

639647
class TupleMeta(TypingMeta):
640648
"""Metaclass for Tuple."""
@@ -734,6 +742,8 @@ class Tuple(Final, metaclass=TupleMeta, _root=True):
734742
To specify a variable-length tuple of homogeneous type, use Sequence[T].
735743
"""
736744

745+
__slots__ = ()
746+
737747

738748
class CallableMeta(TypingMeta):
739749
"""Metaclass for Callable."""
@@ -767,7 +777,10 @@ def _has_type_var(self):
767777
def _eval_type(self, globalns, localns):
768778
if self.__args__ is None and self.__result__ is None:
769779
return self
770-
args = [_eval_type(t, globalns, localns) for t in self.__args__]
780+
if self.__args__ is Ellipsis:
781+
args = self.__args__
782+
else:
783+
args = [_eval_type(t, globalns, localns) for t in self.__args__]
771784
result = _eval_type(self.__result__, globalns, localns)
772785
if args == self.__args__ and result == self.__result__:
773786
return self
@@ -837,6 +850,8 @@ class Callable(Final, metaclass=CallableMeta, _root=True):
837850
such function types are rarely used as callback types.
838851
"""
839852

853+
__slots__ = ()
854+
840855

841856
def _gorg(a):
842857
"""Return the farthest origin of a generic class."""
@@ -1041,6 +1056,8 @@ def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y:
10411056
# Same body as above.
10421057
"""
10431058

1059+
__slots__ = ()
1060+
10441061
def __new__(cls, *args, **kwds):
10451062
next_in_mro = object
10461063
# Look for the last occurrence of Generic or Generic[...].
@@ -1207,6 +1224,7 @@ def _get_protocol_attrs(self):
12071224
attr != '__abstractmethods__' and
12081225
attr != '_is_protocol' and
12091226
attr != '__dict__' and
1227+
attr != '__slots__' and
12101228
attr != '_get_protocol_attrs' and
12111229
attr != '__parameters__' and
12121230
attr != '__origin__' and
@@ -1224,6 +1242,8 @@ class _Protocol(metaclass=_ProtocolMeta):
12241242
such as Hashable).
12251243
"""
12261244

1245+
__slots__ = ()
1246+
12271247
_is_protocol = True
12281248

12291249

@@ -1234,56 +1254,63 @@ class _Protocol(metaclass=_ProtocolMeta):
12341254

12351255

12361256
class Iterable(Generic[T_co], extra=collections_abc.Iterable):
1237-
pass
1257+
__slots__ = ()
12381258

12391259

12401260
class Iterator(Iterable[T_co], extra=collections_abc.Iterator):
1241-
pass
1261+
__slots__ = ()
12421262

12431263

12441264
class SupportsInt(_Protocol):
1265+
__slots__ = ()
12451266

12461267
@abstractmethod
12471268
def __int__(self) -> int:
12481269
pass
12491270

12501271

12511272
class SupportsFloat(_Protocol):
1273+
__slots__ = ()
12521274

12531275
@abstractmethod
12541276
def __float__(self) -> float:
12551277
pass
12561278

12571279

12581280
class SupportsComplex(_Protocol):
1281+
__slots__ = ()
12591282

12601283
@abstractmethod
12611284
def __complex__(self) -> complex:
12621285
pass
12631286

12641287

12651288
class SupportsBytes(_Protocol):
1289+
__slots__ = ()
12661290

12671291
@abstractmethod
12681292
def __bytes__(self) -> bytes:
12691293
pass
12701294

12711295

12721296
class SupportsAbs(_Protocol[T]):
1297+
__slots__ = ()
12731298

12741299
@abstractmethod
12751300
def __abs__(self) -> T:
12761301
pass
12771302

12781303

12791304
class SupportsRound(_Protocol[T]):
1305+
__slots__ = ()
12801306

12811307
@abstractmethod
12821308
def __round__(self, ndigits: int = 0) -> T:
12831309
pass
12841310

12851311

12861312
class Reversible(_Protocol[T]):
1313+
__slots__ = ()
12871314

12881315
@abstractmethod
12891316
def __reversed__(self) -> 'Iterator[T]':
@@ -1294,7 +1321,7 @@ def __reversed__(self) -> 'Iterator[T]':
12941321

12951322

12961323
class Container(Generic[T_co], extra=collections_abc.Container):
1297-
pass
1324+
__slots__ = ()
12981325

12991326

13001327
# Callable was defined earlier.
@@ -1368,6 +1395,7 @@ def __subclasscheck__(self, cls):
13681395

13691396

13701397
class FrozenSet(frozenset, AbstractSet[T_co], metaclass=_FrozenSetMeta):
1398+
__slots__ = ()
13711399

13721400
def __new__(cls, *args, **kwds):
13731401
if _geqv(cls, FrozenSet):
@@ -1415,6 +1443,7 @@ def __new__(cls, *args, **kwds):
14151443

14161444
class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
14171445
extra=_G_base):
1446+
__slots__ = ()
14181447

14191448
def __new__(cls, *args, **kwds):
14201449
if _geqv(cls, Generator):
@@ -1458,6 +1487,8 @@ class IO(Generic[AnyStr]):
14581487
way to track the other distinctions in the type system.
14591488
"""
14601489

1490+
__slots__ = ()
1491+
14611492
@abstractproperty
14621493
def mode(self) -> str:
14631494
pass
@@ -1542,6 +1573,8 @@ def __exit__(self, type, value, traceback) -> None:
15421573
class BinaryIO(IO[bytes]):
15431574
"""Typed version of the return of open() in binary mode."""
15441575

1576+
__slots__ = ()
1577+
15451578
@abstractmethod
15461579
def write(self, s: Union[bytes, bytearray]) -> int:
15471580
pass
@@ -1554,6 +1587,8 @@ def __enter__(self) -> 'BinaryIO':
15541587
class TextIO(IO[str]):
15551588
"""Typed version of the return of open() in text mode."""
15561589

1590+
__slots__ = ()
1591+
15571592
@abstractproperty
15581593
def buffer(self) -> BinaryIO:
15591594
pass

0 commit comments

Comments
 (0)