cut stringclasses 1
value | version stringclasses 10
values | idiom_id stringclasses 53
values | pep stringclasses 53
values | introduced_in stringclasses 11
values | form stringclasses 2
values | file stringclasses 887
values | code stringclasses 916
values | source stringclasses 1
value | origin stringlengths 15 17 | origin_revision stringclasses 10
values | license stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | 3.11 | type-hints | 484 | 3.5 | modern | type-hints/modern_56.py | UserId = NewType('UserId', int)
def name_by_id(user_id: UserId) -> str:
...
UserId('user') # Fails type check
name_by_id(42) # Fails type check
name_by_id(UserId(42)) # OK
num = UserId(5) + 1 # type: int
| pydocs | pep-0484.txt:1579 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | type-hints | 484 | 3.5 | modern | type-hints/modern_57.py | class PacketId:
def __init__(self, major: int, minor: int) -> None:
self._major = major
self._minor = minor
TcpPacketId = NewType('TcpPacketId', PacketId)
packet = PacketId(100, 100)
tcp_packet = TcpPacketId(packet) # OK
tcp_packet = TcpPacketId(127, 0) # Fails in type checker and at runtime
| pydocs | pep-0484.txt:1598 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | type-hints | 484 | 3.5 | modern | type-hints/modern_58.py | def __getattr__(name) -> Any: ...
| pydocs | pep-0484.txt:1680 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | type-hints | 484 | 3.5 | modern | type-hints/modern_59.py | from typing import overload
class bytes:
...
@overload
def __getitem__(self, i: int) -> int: ...
@overload
def __getitem__(self, s: slice) -> bytes: ...
| pydocs | pep-0484.txt:1694 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | type-hints | 484 | 3.5 | modern | type-hints/modern_60.py | from typing import Union
class bytes:
...
def __getitem__(self, a: Union[int, slice]) -> Union[int, bytes]: ...
| pydocs | pep-0484.txt:1707 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | type-hints | 484 | 3.5 | modern | type-hints/modern_61.py | from typing import Callable, Iterable, Iterator, Tuple, TypeVar, overload
T1 = TypeVar('T1')
T2 = TypeVar('T2')
S = TypeVar('S')
@overload
def map(func: Callable[[T1], S], iter1: Iterable[T1]) -> Iterator[S]: ...
@overload
def map(func: Callable[[T1, T2], S],
iter1: Iterable[T1], iter2: Iterable[T2]) -> Itera... | pydocs | pep-0484.txt:1717 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | type-hints | 484 | 3.5 | modern | type-hints/modern_62.py | @overload
def map(func: None, iter1: Iterable[T1]) -> Iterable[T1]: ...
@overload
def map(func: None,
iter1: Iterable[T1],
iter2: Iterable[T2]) -> Iterable[Tuple[T1, T2]]: ...
| pydocs | pep-0484.txt:1732 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | type-hints | 484 | 3.5 | modern | type-hints/modern_63.py | from typing import TypeVar, Text
AnyStr = TypeVar('AnyStr', Text, bytes)
def concat1(x: AnyStr, y: AnyStr) -> AnyStr: ...
@overload
def concat2(x: str, y: str) -> str: ...
@overload
def concat2(x: bytes, y: bytes) -> bytes: ...
| pydocs | pep-0484.txt:1781 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | type-hints | 484 | 3.5 | legacy | type-hints/legacy_09.py | def add(a, b): # type: (int, int) -> int
return a + b
| pydocs | pep-0484.txt:2163 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | type-hints | 484 | 3.5 | legacy | type-hints/legacy_10.py | def f():
'''Docstring'''
# type: () -> None # Error!
def g():
'''Docstring'''
# # type: () -> None # This is OK
| pydocs | pep-0484.txt:2169 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | type-hints | 484 | 3.5 | modern | type-hints/modern_64.py | class Node:
"""Binary tree node."""
def __init__(self, left: Node, right: Node):
self.left = left
self.right = right
| pydocs | pep-0484.txt:2312 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | type-hints | 484 | 3.5 | modern | type-hints/modern_65.py | from __future__ import annotations
class ImSet:
def add(self, a: ImSet) -> List[ImSet]: ...
assert ImSet.add.__annotations__ == {'a': 'ImSet', 'return': 'List[ImSet]'}
| pydocs | pep-0484.txt:2338 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | numeric-underscores | 515 | 3.6 | modern | numeric-underscores/modern_01.py | # grouping decimal numbers by thousands
amount = 10_000_000.0
# grouping hexadecimal addresses by words
addr = 0xCAFE_F00D
# grouping bits into nibbles in a binary literal
flags = 0b_0011_1111_0100_1110
# same, for string conversions
flags = int('0b_1111_0000', 2)
| pydocs | pep-0515.txt:27 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | legacy | variable-annotations/legacy_01.py | # 'primes' is a list of integers
primes = [] # type: List[int]
# 'captain' is a string (Note: initial value is a problem)
captain = ... # type: str
class Starship:
# 'stats' is a class variable
stats = {} # type: Dict[str, int]
| pydocs | pep-0526.txt:44 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_01.py | primes: List[int] = []
captain: str # Note: no initial value!
class Starship:
stats: ClassVar[Dict[str, int]] = {}
| pydocs | pep-0526.txt:58 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | legacy | variable-annotations/legacy_02.py | if some_value:
my_var = function() # type: Logger
else:
my_var = another_function() # Why isn't there a type here?
| pydocs | pep-0526.txt:85 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | legacy | variable-annotations/legacy_03.py | path = None # type: Optional[str] # Path to module source
| pydocs | pep-0526.txt:101 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_02.py | my_var: int
my_var = 5 # Passes type check.
other_var: int = 'a' # Flagged as error by type checker,
# but OK at runtime.
| pydocs | pep-0526.txt:140 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_03.py | var = value # type: annotation
var: annotation; var = value
var: annotation = value
| pydocs | pep-0526.txt:148 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_04.py | some_number: int # variable without initial value
some_list: List[int] = [] # variable with initial value
| pydocs | pep-0526.txt:164 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_05.py | sane_world: bool
if 2+2 == 4:
sane_world = True
else:
sane_world = False
| pydocs | pep-0526.txt:170 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_06.py | # Tuple packing with variable annotation syntax
t: Tuple[int, ...] = (1, 2, 3)
# or
t: Tuple[int, ...] = 1, 2, 3 # This only works in Python 3.8+
# Tuple unpacking with variable annotation syntax
header: str
kind: int
body: Optional[List[str]]
header, kind, body = message
| pydocs | pep-0526.txt:179 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_07.py | a: int
print(a) # raises NameError
| pydocs | pep-0526.txt:192 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_08.py | def f():
a: int
print(a) # raises UnboundLocalError
# Commenting out the a: int makes it a NameError.
| pydocs | pep-0526.txt:198 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_09.py | a: int
a: str # Static type checker may or may not warn about this.
| pydocs | pep-0526.txt:213 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_10.py | class BasicStarship:
captain: str = 'Picard' # instance variable with default
damage: int # instance variable without default
stats: ClassVar[Dict[str, int]] = {} # class variable
| pydocs | pep-0526.txt:226 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_11.py | class Starship:
captain: str = 'Picard'
damage: int
stats: ClassVar[Dict[str, int]] = {}
def __init__(self, damage: int, captain: str = None):
self.damage = damage
if captain:
self.captain = captain # Else keep the default
def hit(self):
Starship.stats['hits'] ... | pydocs | pep-0526.txt:267 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_12.py | from typing import Generic, TypeVar
T = TypeVar('T')
class Box(Generic[T]):
def __init__(self, content):
self.content: T = content
| pydocs | pep-0526.txt:287 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_13.py | class Cls:
pass
c = Cls()
c.x: int = 0 # Annotates c.x with int.
c.y: int # Annotates c.y with int.
d = {}
d['a']: int = 0 # Annotates d['a'] with int.
d['b']: int # Annotates d['b'] with int.
| pydocs | pep-0526.txt:301 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_14.py | (x): int # Annotates x with int, (x) treated as expression by compiler.
(y): int = 0 # Same situation here.
| pydocs | pep-0526.txt:315 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_15.py | a: int
for a in my_iter:
...
f: MyFile
with myfunc() as f:
...
| pydocs | pep-0526.txt:339 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_16.py | # file lib.pyi
ADDRESS: unicode = ...
class Error:
cause: Union[str, unicode]
| pydocs | pep-0526.txt:356 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_17.py | code: int
class Point:
coords: Tuple[int, int]
label: str = '<unknown>'
| pydocs | pep-0526.txt:374 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_18.py | code:int # No space after colon
code : int # Space before colon
class Test:
result: int=0 # No spaces around equality sign
| pydocs | pep-0526.txt:382 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_19.py | def f():
x: NonexistentName # No error.
| pydocs | pep-0526.txt:423 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_20.py | x: NonexistentName # Error!
class X:
var: NonexistentName # Error!
| pydocs | pep-0526.txt:429 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_21.py | from typing import Dict
class Player:
...
players: Dict[str, Player]
__points: int
print(__annotations__)
# prints: {'players': typing.Dict[str, __main__.Player],
# '_Player__points': <class 'int'>}
| pydocs | pep-0526.txt:439 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_22.py | class C:
__annotations__ = 42
x: int = 5 # raises TypeError
| pydocs | pep-0526.txt:456 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_23.py | from typing import Dict, ClassVar, get_type_hints
class Starship:
hitpoints: int = 50
stats: ClassVar[Dict[str, int]] = {}
shield: int = 100
captain: str
def __init__(self, captain: str) -> None:
...
assert get_type_hints(Starship) == {'hitpoints': int,
'... | pydocs | pep-0526.txt:470 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_24.py | alice: 'well done' = 'A+'
bob: 'what a shame' = 'F-'
| pydocs | pep-0526.txt:499 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | variable-annotations | 526 | 3.6 | modern | variable-annotations/modern_25.py | def foo(self):
slef.name: str
| pydocs | pep-0526.txt:659 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | legacy | protocol/legacy_01.py | from typing import Sized, Iterable, Iterator
class Bucket(Sized, Iterable[int]):
...
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[int]: ...
| pydocs | pep-0544.txt:39 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | legacy | protocol/legacy_02.py | from zope.interface import Interface, Attribute, implementer
class IEmployee(Interface):
name = Attribute("Name of employee")
def do(work):
"""Do some work"""
@implementer(IEmployee)
class Employee:
name = 'Anonymous'
def do(self, work):
return work.start()
| pydocs | pep-0544.txt:128 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | legacy | protocol/legacy_03.py | from zope.interface import invariant
def required_contact(obj):
if not (obj.email or obj.phone):
raise Exception("At least one contact info is required")
class IPerson(Interface):
name = Attribute("Name")
email = Attribute("Email Address")
phone = Attribute("Phone Number")
invariant(requ... | pydocs | pep-0544.txt:148 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | legacy | protocol/legacy_04.py | from abc import ABC
class MyTuple(ABC):
pass
MyTuple.register(tuple)
assert issubclass(tuple, MyTuple)
assert isinstance((), MyTuple)
| pydocs | pep-0544.txt:174 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_01.py | from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None:
...
| pydocs | pep-0544.txt:293 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_02.py | from typing import Protocol
from abc import abstractmethod
class Example(Protocol):
def first(self) -> int: # This is a protocol member
return 42
@abstractmethod
def second(self) -> int: # Method without a default implementation
raise NotImplementedError
| pydocs | pep-0544.txt:338 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_03.py | from typing import Protocol, List
class Template(Protocol):
name: str # This is a protocol member
value: int = 0 # This one too (with default)
def method(self) -> None:
self.temp: List[int] = [] # Error in type checker
class Concrete:
def __init__(self, name: str, value: int) -> None... | pydocs | pep-0544.txt:359 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_04.py | class PColor(Protocol):
@abstractmethod
def draw(self) -> str:
...
def complex_method(self) -> int:
...
# some complex code here
class NiceColor(PColor):
def draw(self) -> str:
return "deep blue"
class BadColor(PColor):
def draw(self) -> str:
return super().... | pydocs | pep-0544.txt:399 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_05.py | class RGB(Protocol):
rgb: Tuple[int, int, int]
@abstractmethod
def intensity(self) -> int:
return 0
class Point(RGB):
def __init__(self, red: int, green: int, blue: str) -> None:
self.rgb = red, green, blue # Error, 'blue' must be 'int'
# Type checker might warn that 'intensity' ... | pydocs | pep-0544.txt:434 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_06.py | from typing import Sized, Protocol
class SizedAndClosable(Sized, Protocol):
def close(self) -> None:
...
| pydocs | pep-0544.txt:471 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_07.py | from typing import Sized
class SupportsClose(Protocol):
def close(self) -> None:
...
class SizedAndClosable(Sized, SupportsClose, Protocol):
pass
| pydocs | pep-0544.txt:484 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_08.py | class Iterable(Protocol[T]):
@abstractmethod
def __iter__(self) -> Iterator[T]:
...
| pydocs | pep-0544.txt:513 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_09.py | T = TypeVar('T')
T_co = TypeVar('T_co', covariant=True)
T_contra = TypeVar('T_contra', contravariant=True)
class Box(Protocol[T_co]):
def content(self) -> T_co:
...
box: Box[float]
second_box: Box[int]
box = second_box # This is OK due to the covariance of 'Box'.
class Sender(Protocol[T_contra]):
de... | pydocs | pep-0544.txt:525 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_10.py | T = TypeVar('T')
class AnotherBox(Protocol[T]): # Error, this protocol is covariant in T,
def content(self) -> T: # not invariant.
...
| pydocs | pep-0544.txt:556 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_11.py | class Traversable(Protocol):
def leaves(self) -> Iterable['Traversable']:
...
| pydocs | pep-0544.txt:571 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_12.py | C = TypeVar('C', bound='Copyable')
class Copyable(Protocol):
def copy(self: C) -> C:
...
class One:
def copy(self) -> 'One':
...
T = TypeVar('T', bound='Other')
class Other:
def copy(self: T) -> T:
...
c: Copyable
c = One() # OK
c = Other() # Also OK
| pydocs | pep-0544.txt:602 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_13.py | from typing import Optional, List, Protocol
class Combiner(Protocol):
def __call__(self, *vals: bytes,
maxlen: Optional[int] = None) -> List[bytes]: ...
def good_cb(*vals: bytes, maxlen: Optional[int] = None) -> List[bytes]:
...
def bad_cb(*vals: bytes, maxitems: Optional[int]) -> List[bytes]... | pydocs | pep-0544.txt:628 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_14.py | # file lib.py
from typing import Sized
T = TypeVar('T', contravariant=True)
class ListLike(Sized, Protocol[T]):
def append(self, x: T) -> None:
pass
def populate(lst: ListLike[int]) -> None:
...
# file main.py
from lib import populate # Note that ListLike is NOT imported
class MockStack:
def __... | pydocs | pep-0544.txt:674 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_15.py | from typing import Union, Optional, Protocol
class Exitable(Protocol):
def exit(self) -> int:
...
class Quittable(Protocol):
def quit(self) -> Optional[int]:
...
def finish(task: Union[Exitable, Quittable]) -> int:
...
class DefaultJob:
...
def quit(self) -> int:
return 0
f... | pydocs | pep-0544.txt:704 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_16.py | from typing import Iterable, Hashable
class HashableFloats(Iterable[float], Hashable, Protocol):
pass
def cached_func(args: HashableFloats) -> float:
...
cached_func((1, 2, 3)) # OK, tuple is both hashable and iterable
| pydocs | pep-0544.txt:724 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_17.py | class Proto(Protocol):
@abstractmethod
def meth(self) -> int:
...
class Concrete:
def meth(self) -> int:
return 42
def fun(cls: Type[Proto]) -> int:
return cls().meth() # OK
fun(Proto) # Error
fun(Concrete) # OK
| pydocs | pep-0544.txt:745 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_18.py | from typing import Any, Protocol
class ProtoA(Protocol):
def meth(self, x: int) -> int: ...
class ProtoB(Protocol):
def meth(self, obj: Any, x: int) -> int: ...
class C:
def meth(self, x: int) -> int: ...
a: ProtoA = C # Type check error, signatures don't match!
b: ProtoB = C # OK
| pydocs | pep-0544.txt:774 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_19.py | from typing import NewType, Protocol, Iterator
class Id(Protocol):
code: int
secrets: Iterator[bytes]
UserId = NewType('UserId', Id) # Error, can't provide distinct type
| pydocs | pep-0544.txt:795 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_20.py | from typing import TypeVar, Reversible, Iterable, Sized
T = TypeVar('T')
class SizedIterable(Iterable[T], Sized, Protocol):
pass
CompatReversible = Union[Reversible[T], SizedIterable[T]]
| pydocs | pep-0544.txt:806 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_21.py | # file default_config.py
timeout = 100
one_flag = True
other_flag = False
# file main.py
import default_config
from typing import Protocol
class Options(Protocol):
timeout: int
one_flag: bool
other_flag: bool
def setup(options: Options) -> None:
...
setup(default_config) # OK
| pydocs | pep-0544.txt:821 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_22.py | # callbacks.py
def on_error(x: int) -> None:
...
def on_success() -> None:
...
# main.py
import callbacks
from typing import Protocol
class Reporter(Protocol):
def on_error(self, x: int) -> None:
...
def on_success(self) -> None:
...
rp: Reporter = callbacks # Passes type check
| pydocs | pep-0544.txt:843 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_23.py | from typing import runtime_checkable, Protocol
@runtime_checkable
class SupportsClose(Protocol):
def close(self):
...
assert isinstance(open('some/file'), SupportsClose)
| pydocs | pep-0544.txt:881 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_24.py | class Foo(Protocol):
@property
def c(self) -> int:
return 42 # Default value can be provided for property...
@abstractproperty
def d(self) -> int: # ... or it can be abstract
return 0
| pydocs | pep-0544.txt:939 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_25.py | from typing import Protocol
class Base:
attr: str
class Proto(Base, Protocol):
def meth(self) -> int:
...
class C:
attr: str
def meth(self) -> int:
return 0
| pydocs | pep-0544.txt:1076 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_26.py | class Proto(Protocol):
@abstractmethod
def first(self) -> int:
raise NotImplementedError
def second(self) -> int:
return self.first() + 1
def fun(arg: Proto) -> None:
arg.second()
| pydocs | pep-0544.txt:1148 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_27.py | class P(Protocol):
x: int
class C:
def initialize(self) -> None:
self.x = 0
c = C()
isinstance(c, P) # False
c.initialize()
isinstance(c, P) # True
def f(x: Union[P, int]) -> None:
if isinstance(x, P):
# Static type of x is P here.
...
else:
# Static type of x is int... | pydocs | pep-0544.txt:1235 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_28.py | class Proto(Proto1, Proto2, ..., Protocol):
pass
| pydocs | pep-0544.txt:1272 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_29.py | class P(Protocol):
x: float
def f(arg: P) -> None:
arg.x = 0.42
class C:
x: int
c = C()
f(c) # Would typecheck if covariant subtyping
# of mutable attributes were allowed.
c.x >> 1 # But this fails at runtime
| pydocs | pep-0544.txt:1315 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_30.py | T = TypeVar('T')
class P(Protocol[T]): # Protocol is declared as invariant.
def meth(self) -> T:
...
class C:
def meth(self) -> float:
...
class D(C):
def meth(self) -> int:
...
| pydocs | pep-0544.txt:1343 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | protocol | 544 | 3.8 | modern | protocol/modern_31.py | class OldIterable(Sized, Protocol[T]):
def __getitem__(self, item: int) -> T: ...
CompatIterable = Union[Iterable[T], OldIterable[T]]
class A:
def __iter__(self) -> Iterator[str]: ...
class B:
def __len__(self) -> int: ...
def __getitem__(self, item: int) -> str: ...
def iterate(it: CompatIterable[st... | pydocs | pep-0544.txt:1390 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | positional-only-params | 570 | 3.8 | modern | positional-only-params/modern_01.py | def name(positional_only_parameters, /, positional_or_keyword_parameters,
*, keyword_only_parameters):
...
| pydocs | pep-0570.rst:443 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | positional-only-params | 570 | 3.8 | modern | positional-only-params/modern_02.py | def name(p1, p2, /, p_or_kw, *, kw):
...
def name(p1, p2=None, /, p_or_kw=None, *, kw):
...
def name(p1, p2=None, /, *, kw):
...
def name(p1, p2=None, /):
...
def name(p1, p2, /, p_or_kw):
...
def name(p1, p2, /):
...
| pydocs | pep-0570.rst:461 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | positional-only-params | 570 | 3.8 | modern | positional-only-params/modern_03.py | def foo(name, /, **kwds):
return 'name' in kwds
| pydocs | pep-0570.rst:539 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | positional-only-params | 570 | 3.8 | modern | positional-only-params/modern_04.py | def standard_arg(arg):
print(arg)
def pos_only_arg(arg, /):
print(arg)
def kwd_only_arg(*, arg):
print(arg)
def combined_example(pos_only, /, standard, *, kwd_only):
print(pos_only, standard, kwd_only)
| pydocs | pep-0570.rst:635 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | positional-only-params | 570 | 3.8 | modern | positional-only-params/modern_05.py | def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
...
| pydocs | pep-0570.rst:705 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | builtin-generics | 585 | 3.9 | modern | builtin-generics/modern_01.py | from __future__ import annotations
def find(haystack: dict[str, list[int]]) -> int:
...
| pydocs | pep-0585.rst:67 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | builtin-generics | 585 | 3.9 | modern | builtin-generics/modern_02.py | list[str]
tuple[int, ...]
ChainMap[str, list[str]]
| pydocs | pep-0585.rst:143 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | builtin-generics | 585 | 3.9 | modern | builtin-generics/modern_03.py | l = list[str]()
list is list[str]
list == list[str]
list[str] == list[str]
list[str] == list[int]
isinstance([1, 2, 3], list[str])
issubclass(list, list[str])
isinstance(list[str], types.GenericAlias)
| pydocs | pep-0585.rst:168 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | builtin-generics | 585 | 3.9 | modern | builtin-generics/modern_04.py | l: list[str] = []
| pydocs | pep-0585.rst:194 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | builtin-generics | 585 | 3.9 | modern | builtin-generics/modern_05.py | l = list[str]()
| pydocs | pep-0585.rst:198 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | builtin-generics | 585 | 3.9 | modern | builtin-generics/modern_06.py | list[str]
tuple[int, ...]
collections.ChainMap[str, list[str]]
| pydocs | pep-0585.rst:244 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | builtin-generics | 585 | 3.9 | legacy | builtin-generics/legacy_01.py | from typing import List, Tuple, ChainMap
List[str]
Tuple[int, ...]
ChainMap[str, List[str]]
| pydocs | pep-0585.rst:255 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | builtin-generics | 585 | 3.9 | modern | builtin-generics/modern_07.py | isinstance([1, 2, 3], list[str])
| pydocs | pep-0585.rst:323 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | literal-types | 586 | 3.8 | modern | literal-types/modern_01.py | from typing import Literal
def accepts_only_four(x: Literal[4]) -> None:
pass
accepts_only_four(4) # OK
accepts_only_four(19) # Rejected
| pydocs | pep-0586.rst:24 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | literal-types | 586 | 3.8 | modern | literal-types/modern_02.py | # Note: this is a simplification of the true type signature.
_PathType = Union[str, bytes, int]
@overload
def open(path: _PathType,
mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+"],
) -> IO[Text]: ...
@overload
def open(path: _PathType,
mode: Literal["rb", "wb", "ab", "xb", "r+b", "... | pydocs | pep-0586.rst:126 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | literal-types | 586 | 3.8 | modern | literal-types/modern_03.py | Literal[26]
Literal[0x1A] # Exactly equivalent to Literal[26]
Literal[-4]
Literal["hello world"]
Literal[b"hello world"]
Literal[u"hello world"]
Literal[True]
Literal[Color.RED] # Assuming Color is some enum
Literal[None]
| pydocs | pep-0586.rst:166 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | literal-types | 586 | 3.8 | modern | literal-types/modern_04.py | ReadOnlyMode = Literal["r", "r+"]
WriteAndTruncateMode = Literal["w", "w+", "wt", "w+t"]
WriteNoTruncateMode = Literal["r+", "r+t"]
AppendMode = Literal["a", "a+", "at", "a+t"]
AllModes = Literal[ReadOnlyMode, WriteAndTruncateMode,
WriteNoTruncateMode, AppendMode]
| pydocs | pep-0586.rst:183 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | literal-types | 586 | 3.8 | modern | literal-types/modern_05.py | Literal[Literal[Literal[1, 2, 3], "foo"], 5, None]
| pydocs | pep-0586.rst:197 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | literal-types | 586 | 3.8 | modern | literal-types/modern_06.py | Literal[1, 2, 3, "foo", 5, None]
| pydocs | pep-0586.rst:201 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | literal-types | 586 | 3.8 | modern | literal-types/modern_07.py | Optional[Literal[1, 2, 3, "foo", 5]]
| pydocs | pep-0586.rst:205 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | literal-types | 586 | 3.8 | modern | literal-types/modern_08.py | def my_function(x: Literal[1 + 2]) -> int:
return x * 3
x: Literal = 3
y: Literal[my_function] = my_function
| pydocs | pep-0586.rst:272 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | literal-types | 586 | 3.8 | modern | literal-types/modern_09.py | def expects_str(x: str) -> None: ...
var: Literal["foo"] = "foo"
# Legal: Literal["foo"] is a subtype of str
expects_str(var)
| pydocs | pep-0586.rst:361 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | literal-types | 586 | 3.8 | modern | literal-types/modern_10.py | def expects_literal(x: Literal["foo"]) -> None: ...
def runner(my_str: str) -> None:
# ILLEGAL: str is not a subclass of Literal["foo"]
expects_literal(my_str)
| pydocs | pep-0586.rst:370 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
train | 3.11 | literal-types | 586 | 3.8 | modern | literal-types/modern_11.py | a: Literal[0] = 0
b: Literal[5] = 5
some_tuple: Tuple[int, str, List[bool]] = (3, "abc", [True, False])
reveal_type(some_tuple[a]) # Revealed type is 'int'
some_tuple[b] # Error: 5 is not a valid index into the tuple
| pydocs | pep-0586.rst:394 | 1a931bf317c851a907067308cb1175deeb9415c6 | CC0-1.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.