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.6 | fstring | 498 | 3.6 | modern | fstring/modern_02.py | f'The value is {value}.'
| pydocs | pep-0498.txt:103 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_03.py | value = 1234
f'input={value:#0.6x}'
| pydocs | pep-0498.txt:118 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_04.py | date = datetime.date(1991, 10, 12)
f'{date} was on a {date:%A}'
| pydocs | pep-0498.txt:125 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | legacy | fstring/legacy_06.py | def outer(x):
def inner():
return 'x={x}'.format_map(locals())
return inner
outer(42)()
| pydocs | pep-0498.txt:137 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | legacy | fstring/legacy_07.py | def outer(x):
def inner():
x
return 'x={x}'.format_map(locals())
return inner
outer(42)()
| pydocs | pep-0498.txt:152 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_05.py | f'{"quoted string"}'
| pydocs | pep-0498.txt:250 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_06.py | f'{{ {4*10} }}'
f'{{{4*10}}}'
| pydocs | pep-0498.txt:259 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_07.py | fr'x={4*10}\n'
| pydocs | pep-0498.txt:267 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_08.py | f"abc {a['x']} def"
| pydocs | pep-0498.txt:277 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_09.py | f'''abc {a['x']} def'''
| pydocs | pep-0498.txt:281 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_10.py | f'abc{expr1:spec1}{expr2!r:spec2}def{expr3}ghi'
| pydocs | pep-0498.txt:293 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_11.py | def foo():
return 20
f'result={foo()}'
| pydocs | pep-0498.txt:313 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_12.py | x = 0
f'''{x
+1}'''
d = {0: 'zero'}
f'''{d[0
]}'''
| pydocs | pep-0498.txt:330 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_13.py | width = 10
precision = 4
value = decimal.Decimal('12.34567')
f'result: {value:{width}.{precision}}'
| pydocs | pep-0498.txt:346 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_14.py | x = 10
y = 'hi'
'a' 'b' f'{x}' '{c}' f'str<{y:^4}>' 'd' 'e'
| pydocs | pep-0498.txt:364 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_15.py | d = {0:10, 1:20}
for i in range(3):
print(f'{i}:{d[i]}')
| pydocs | pep-0498.txt:409 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_16.py | for x in (32, 100, 'fifty'):
print(f'x = {x:+3}')
| pydocs | pep-0498.txt:421 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_17.py | def fn(l, incr):
result = l[0]
l[0] += incr
return result
lst = [0]
f'{fn(lst,2)} {fn(lst,3)}'
f'{fn(lst,2)} {fn(lst,3)}'
lst
| pydocs | pep-0498.txt:443 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_18.py | f'Column={col_idx+1}'
f'number of items: {len(items)}'
| pydocs | pep-0498.txt:517 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_19.py | col_number = col_idx+1
f'Column={col_number}'
n_items = len(items)
f'number of items: {n_items}'
| pydocs | pep-0498.txt:522 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_20.py | f'mapping is { {a:b for (a, b) in ((1, 2), (3, 4))} }'
| pydocs | pep-0498.txt:531 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | legacy | fstring/legacy_08.py | d = {'a': 10, 'b': 20}
'a={d[a]}'.format(d=d)
| pydocs | pep-0498.txt:550 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_21.py | f'a={d["a"]}'
| pydocs | pep-0498.txt:560 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_22.py | a = 'b'
f'a={d[a]}'
| pydocs | pep-0498.txt:566 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | legacy | fstring/legacy_09.py | '{i[";]}'.format(i={'";':4})
| pydocs | pep-0498.txt:576 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_23.py | header = 'Subject'
fr'{header}:\s+'
| pydocs | pep-0498.txt:596 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_24.py | a = 'some string'
f'{a!r}'
| pydocs | pep-0498.txt:631 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_25.py | f'{repr(a)}'
| pydocs | pep-0498.txt:637 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_26.py | f'{(lambda x: x*2)(3)}'
| pydocs | pep-0498.txt:660 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_27.py | extra = '{},waiters:{}'.format(extra, len(self._waiters))
extra = f'{extra},waiters:{len(self._waiters)}'
| pydocs | pep-0498.txt:682 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_28.py | message.append(" [line {0:2d}]".format(lineno))
message.append(f" [line {lineno:2d}]")
| pydocs | pep-0498.txt:687 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_29.py | methoddef_name = "{}_METHODDEF".format(c_basename.upper())
methoddef_name = f"{c_basename.upper()}_METHODDEF"
| pydocs | pep-0498.txt:692 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | fstring | 498 | 3.6 | modern | fstring/modern_30.py | print("Usage: {0} [{1}]".format(sys.argv[0], '|'.join('--'+opt for opt in valid_opts)), file=sys.stderr)
print(f"Usage: {sys.argv[0]} [{'|'.join('--'+opt for opt in valid_opts)}]", file=sys.stderr)
| pydocs | pep-0498.txt:697 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | async-generators | 525 | 3.6 | legacy | async-generators/legacy_01.py | class Ticker:
"""Yield numbers from 0 to `to` every `delay` seconds."""
def __init__(self, delay, to):
self.delay = delay
self.i = 0
self.to = to
def __aiter__(self):
return self
async def __anext__(self):
i = self.i
if i >= self.to:
raise S... | pydocs | pep-0525.txt:46 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | async-generators | 525 | 3.6 | modern | async-generators/modern_01.py | async def ticker(delay, to):
"""Yield numbers from 0 to `to` every `delay` seconds."""
for i in range(to):
yield i
await asyncio.sleep(delay)
| pydocs | pep-0525.txt:69 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | async-generators | 525 | 3.6 | modern | async-generators/modern_02.py | async def coro(): # a coroutine function
await smth()
async def asyncgen(): # an asynchronous generator function
await smth()
yield 42
| pydocs | pep-0525.txt:101 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | async-generators | 525 | 3.6 | modern | async-generators/modern_03.py | async def genfunc():
yield 1
yield 2
gen = genfunc()
assert gen.__aiter__() is gen
assert await gen.__anext__() == 1
assert await gen.__anext__() == 2
await gen.__anext__() # This line will raise StopAsyncIteration.
| pydocs | pep-0525.txt:129 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | async-generators | 525 | 3.6 | modern | async-generators/modern_04.py | async def square_series(con, to):
async with con.transaction():
cursor = con.cursor(
'SELECT generate_series(0, $1) AS i', to)
async for row in cursor:
yield row['i'] ** 2
async for i in square_series(con, 1000):
if i == 100:
break
| pydocs | pep-0525.txt:155 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | async-generators | 525 | 3.6 | modern | async-generators/modern_05.py | async def gen():
try:
yield
finally:
await asyncio.sleep(1) # Can use 'await'.
yield # Cannot use 'yield',
# this line will trigger a
# RuntimeError.
| pydocs | pep-0525.txt:191 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | async-generators | 525 | 3.6 | modern | async-generators/modern_06.py | async def gen():
await asyncio.sleep(0.1)
v = yield 42
print(v)
await asyncio.sleep(0.2)
g = gen()
await g.asend(None) # Will return 42 after sleeping
# for 0.1 seconds.
await g.asend('hello') # Will print 'hello' and
# raise StopAsyncIteration... | pydocs | pep-0525.txt:307 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | async-generators | 525 | 3.6 | modern | async-generators/modern_07.py | N = 10 ** 7
async def agen():
for i in range(N):
yield i
class AIter:
def __init__(self):
self.i = 0
def __aiter__(self):
return self
async def __anext__(self):
i = self.i
if i >= N:
raise StopAsyncIteration
self.i += 1
return i
| pydocs | pep-0525.txt:492 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | async-generators | 525 | 3.6 | modern | async-generators/modern_08.py | async def g1():
yield 1
yield 2
async def g2():
async for v in g1():
yield v
| pydocs | pep-0525.txt:553 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | async-generators | 525 | 3.6 | modern | async-generators/modern_09.py | @async_context_manager
async def ctx():
await open()
try:
yield
finally:
await close()
async with ctx():
await ...
| pydocs | pep-0525.txt:570 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | async-generators | 525 | 3.6 | modern | async-generators/modern_10.py | async def ticker(delay, to):
for i in range(to):
yield i
await asyncio.sleep(delay)
async def run():
async for i in ticker(1, 10):
print(i)
import asyncio
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(run())
finally:
loop.close()
| pydocs | pep-0525.txt:599 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | class-creation-hooks | 487 | 3.6 | modern | class-creation-hooks/modern_01.py | class QuestBase:
# this is implicitly a @classmethod (see below for motivation)
def __init_subclass__(cls, swallow, **kwargs):
cls.swallow = swallow
super().__init_subclass__(**kwargs)
class Quest(QuestBase, swallow="african"):
pass
Quest.swallow
| pydocs | pep-0487.txt:69 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | class-creation-hooks | 487 | 3.6 | modern | class-creation-hooks/modern_02.py | import weakref
class WeakAttribute:
def __get__(self, instance, owner):
return instance.__dict__[self.name]()
def __set__(self, instance, value):
instance.__dict__[self.name] = weakref.ref(value)
# this is the new initializer:
def __set_name__(self, owner, name):
self.name = n... | pydocs | pep-0487.txt:110 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | class-creation-hooks | 487 | 3.6 | modern | class-creation-hooks/modern_03.py | class PluginBase:
subclasses = []
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.subclasses.append(cls)
| pydocs | pep-0487.txt:197 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.6 | class-creation-hooks | 487 | 3.6 | modern | class-creation-hooks/modern_04.py | class Trait:
def __init__(self, minimum, maximum):
self.minimum = minimum
self.maximum = maximum
def __get__(self, instance, owner):
return instance.__dict__[self.key]
def __set__(self, instance, value):
if self.minimum < value < self.maximum:
instance.__dict__[... | pydocs | pep-0487.txt:216 | e4c4632b001a0832f85245e6f5cc988fd0f72fe0 | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_01.py | def greeting(name: str) -> str:
return 'Hello ' + name
| pydocs | pep-0484.txt:37 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_02.py | Url = str
def retry(url: Url, retry_count: int) -> None: ...
| pydocs | pep-0484.txt:203 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_03.py | from typing import TypeVar, Iterable, Tuple
T = TypeVar('T', int, float, complex)
Vector = Iterable[Tuple[T, T]]
def inproduct(v: Vector[T]) -> T:
return sum(x*y for x, y in v)
def dilate(v: Vector[T], scale: T) -> Vector[T]:
return ((x * scale, y * scale) for x, y in v)
vec = [] # type: Vector[float]
| pydocs | pep-0484.txt:215 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_04.py | from typing import TypeVar, Iterable, Tuple
T = TypeVar('T', int, float, complex)
def inproduct(v: Iterable[Tuple[T, T]]) -> T:
return sum(x*y for x, y in v)
def dilate(v: Iterable[Tuple[T, T]], scale: T) -> Iterable[Tuple[T, T]]:
return ((x * scale, y * scale) for x, y in v)
vec = [] # type: Iterable[Tuple[... | pydocs | pep-0484.txt:229 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_05.py | from typing import Callable
def feeder(get_next_item: Callable[[], str]) -> None:
...
# Body
def async_query(on_success: Callable[[int], None],
on_error: Callable[[int, Exception], None]) -> None:
...
# Body
| pydocs | pep-0484.txt:247 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_06.py | def partial(func: Callable[..., str], *args) -> Callable[..., str]:
...
# Body
| pydocs | pep-0484.txt:260 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_07.py | from typing import Mapping, Set
def notify_by_email(employees: Set[Employee], overrides: Mapping[str, str]) -> None: ...
| pydocs | pep-0484.txt:287 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_08.py | from typing import Sequence, TypeVar
T = TypeVar('T') # Declare type variable
def first(l: Sequence[T]) -> T: # Generic function
return l[0]
| pydocs | pep-0484.txt:294 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_09.py | from typing import TypeVar
AnyStr = TypeVar('AnyStr', str, bytes)
def concat(x: AnyStr, y: AnyStr) -> AnyStr:
return x + y
| pydocs | pep-0484.txt:315 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_10.py | def count_truthy(elements: List[Any]) -> int:
return sum(1 for elem in elements if elem)
| pydocs | pep-0484.txt:344 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_11.py | from typing import TypeVar, Generic
from logging import Logger
T = TypeVar('T')
class LoggedVar(Generic[T]):
def __init__(self, value: T, name: str, logger: Logger) -> None:
self.name = name
self.logger = logger
self.value = value
def set(self, new: T) -> None:
self.log('Set '... | pydocs | pep-0484.txt:357 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_12.py | from typing import Iterable
def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
for var in vars:
var.set(0)
| pydocs | pep-0484.txt:386 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_13.py | from typing import TypeVar, Generic
T = TypeVar('T')
def fun_1(x: T) -> T: ... # T here
def fun_2(x: T) -> T: ... # and here could be different
fun_1(1) # This is OK, T is inferred to be int
fun_2('a') # This is also OK, now T is str
| pydocs | pep-0484.txt:469 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_14.py | from typing import TypeVar, Generic
T = TypeVar('T')
class MyClass(Generic[T]):
def meth_1(self, x: T) -> T: ... # T here
def meth_2(self, x: T) -> T: ... # and here are always the same
a = MyClass() # type: MyClass[int]
a.meth_1(1) # OK
a.meth_2('a') # This is an error!
| pydocs | pep-0484.txt:483 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_15.py | T = TypeVar('T')
S = TypeVar('S')
class Foo(Generic[T]):
def method(self, x: T, y: S) -> S:
...
x = Foo() # type: Foo[int]
y = x.method(0, "abc") # inferred type of y is str
| pydocs | pep-0484.txt:499 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_16.py | T = TypeVar('T')
S = TypeVar('S')
def a_fun(x: T) -> None:
# this is OK
y = [] # type: List[T]
# but below is an error!
y = [] # type: List[S]
class Bar(Generic[T]):
# this is also an error
an_attr = [] # type: List[S]
def do_something(x: S) -> S: # this is OK though
...
| pydocs | pep-0484.txt:511 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_17.py | from typing import List
def a_fun(x: T) -> None:
# This is OK
a_list = [] # type: List[T]
...
# This is however illegal
class MyGeneric(Generic[T]):
...
| pydocs | pep-0484.txt:530 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_18.py | from typing import TypeVar, Generic
T = TypeVar('T')
class Node(Generic[T]):
x = None # type: T # Instance attribute (see below)
def __init__(self, label: T = None) -> None:
...
x = Node('') # Inferred type is Node[str]
y = Node(0) # Inferred type is Node[int]
z = Node() # Inferred type is No... | pydocs | pep-0484.txt:581 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | legacy | type-hints/legacy_01.py | # (continued from previous example)
a = Node() # type: Node[int]
b = Node() # type: Node[str]
| pydocs | pep-0484.txt:598 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | legacy | type-hints/legacy_02.py | data = collections.defaultdict() # type: DefaultDict[int, bytes]
| pydocs | pep-0484.txt:643 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_19.py | from typing import Dict, List, Optional
class Node:
...
class SymbolTable(Dict[str, List[Node]]):
def push(self, name: str, node: Node) -> None:
self.setdefault(name, []).append(node)
def pop(self, name: str) -> Node:
return self[name].pop()
def lookup(self, name: str) -> Optional[No... | pydocs | pep-0484.txt:662 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_20.py | from typing import TypeVar
class Comparable(metaclass=ABCMeta):
@abstractmethod
def __lt__(self, other: Any) -> bool: ...
... # __gt__ etc. as well
CT = TypeVar('CT', bound=Comparable)
def min(x: CT, y: CT) -> CT:
if x < y:
return x
else:
return y
min(1, 2) # ok, return type int
... | pydocs | pep-0484.txt:728 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_21.py | from typing import TypeVar, Generic, Iterable, Iterator
T_co = TypeVar('T_co', covariant=True)
class ImmutableList(Generic[T_co]):
def __init__(self, items: Iterable[T_co]) -> None: ...
def __iter__(self) -> Iterator[T_co]: ...
...
class Employee: ...
class Manager(Employee): ...
def dump_employees(emp... | pydocs | pep-0484.txt:796 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_22.py | from typing import TypeVar
class Employee: ...
class Manager(Employee): ...
E = TypeVar('E', bound=Employee)
def dump_employee(e: E) -> None: ...
dump_employee(Manager()) # OK
| pydocs | pep-0484.txt:831 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_23.py | B_co = TypeVar('B_co', covariant=True)
def bad_func(x: B_co) -> B_co: # Flagged as error by a type checker
...
| pydocs | pep-0484.txt:845 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_24.py | class Tree:
def __init__(self, left: Tree, right: Tree):
self.left = left
self.right = right
| pydocs | pep-0484.txt:883 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_25.py | class Tree:
def __init__(self, left: 'Tree', right: 'Tree'):
self.left = left
self.right = right
| pydocs | pep-0484.txt:890 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_26.py | class Tree:
...
def leaves(self) -> List['Tree']:
...
| pydocs | pep-0484.txt:909 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_27.py | # File models/a.py
from models.b import B
class A(Model):
def foo(self, b: B): ...
# File models/b.py
from models.a import A
class B(Model):
def bar(self, a: A): ...
# File main.py
from models.a import A
from models.b import B
| pydocs | pep-0484.txt:920 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_28.py | # File models/a.py
from models import b
class A(Model):
def foo(self, b: 'b.B'): ...
# File models/b.py
from models import a
class B(Model):
def bar(self, a: 'a.A'): ...
# File main.py
from models.a import A
from models.b import B
| pydocs | pep-0484.txt:940 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_29.py | from typing import Union
def handle_employees(e: Union[Employee, Sequence[Employee]]) -> None:
if isinstance(e, Employee):
e = [e]
...
| pydocs | pep-0484.txt:962 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_30.py | def handle_employee(e: Union[Employee, None]) -> None: ...
| pydocs | pep-0484.txt:978 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_31.py | from typing import Optional
def handle_employee(e: Optional[Employee]) -> None: ...
| pydocs | pep-0484.txt:983 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_32.py | def handle_employee(e: Employee = None): ...
| pydocs | pep-0484.txt:990 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_33.py | def handle_employee(e: Optional[Employee] = None) -> None: ...
| pydocs | pep-0484.txt:994 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | legacy | type-hints/legacy_03.py | _empty = object()
def func(x=_empty):
if x is _empty: # default argument value
return 0
elif x is None: # argument was provided and it's None
return 1
else:
return x * 2
| pydocs | pep-0484.txt:1004 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_34.py | from typing import Union
from enum import Enum
class Empty(Enum):
token = 0
_empty = Empty.token
def func(x: Union[int, None, Empty] = _empty) -> int:
boom = x * 42 # This fails type check
if x is _empty:
return 0
elif x is None:
return 1
else: # At this point typechecker knows... | pydocs | pep-0484.txt:1018 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_35.py | class Reason(Enum):
timeout = 1
error = 2
def process(response: Union[str, Reason] = '') -> str:
if response is Reason.timeout:
return 'TIMEOUT'
elif response is Reason.error:
return 'ERROR'
else:
# response can be only str, all other possible values exhausted
return... | pydocs | pep-0484.txt:1042 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_36.py | from typing import Mapping
def use_map(m: Mapping) -> None: # Same as Mapping[Any, Any]
...
| pydocs | pep-0484.txt:1074 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_37.py | from typing import Tuple, List, Callable
def check_args(args: Tuple) -> bool:
...
check_args(()) # OK
check_args((42, 'abc')) # Also OK
check_args(3.14) # Flagged as error by a type checker
# A list of arbitrary callables is accepted by this function
def apply_callbacks(cbs: List[Callable]) ->... | pydocs | pep-0484.txt:1084 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_38.py | from typing import NoReturn
def stop() -> NoReturn:
raise RuntimeError('no way')
| pydocs | pep-0484.txt:1105 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_39.py | # continue from first example
def g(x: int) -> int:
if x > 0:
return x
stop()
return 'whatever works' # Error might be not reported by some checkers
# that ignore errors in unreachable blocks
| pydocs | pep-0484.txt:1124 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_40.py | from typing import List, NoReturn
# All of the following are errors
def bad1(x: NoReturn) -> int:
...
bad2 = None # type: NoReturn
def bad3() -> List[NoReturn]:
...
| pydocs | pep-0484.txt:1135 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | legacy | type-hints/legacy_04.py | def new_user(user_class):
user = user_class()
# (Here we could write the user object to a database)
return user
| pydocs | pep-0484.txt:1165 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_41.py | def new_user(user_class: type) -> User:
...
| pydocs | pep-0484.txt:1173 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_42.py | U = TypeVar('U', bound=User)
def new_user(user_class: Type[U]) -> U:
...
| pydocs | pep-0484.txt:1179 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_43.py | def new_non_team_user(user_class: Type[Union[BasicUser, ProUser]]):
user = new_user(user_class)
...
| pydocs | pep-0484.txt:1197 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_44.py | def new_pro_user(pro_user_class: Type[ProUser]):
user = new_user(pro_user_class) # OK
...
| pydocs | pep-0484.txt:1244 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_45.py | T = TypeVar('T', bound='Copyable')
class Copyable:
def copy(self: T) -> T:
...
# return a copy of self
class C(Copyable): ...
c = C()
c2 = c.copy() # type here should be C
| pydocs | pep-0484.txt:1260 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_46.py | T = TypeVar('T', bound='C')
class C:
@classmethod
def factory(cls: Type[T]) -> T:
...
# make a new instance of cls
class D(C): ...
d = D.factory() # type here should be D
| pydocs | pep-0484.txt:1272 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_47.py | import typing
if typing.TYPE_CHECKING:
import expensive_mod
def a_func(arg: 'expensive_mod.SomeClass') -> None:
a_var = arg # type: expensive_mod.SomeClass
...
| pydocs | pep-0484.txt:1317 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
train | 3.7 | type-hints | 484 | 3.5 | modern | type-hints/modern_48.py | def foo(*args: str, **kwds: int): ...
| pydocs | pep-0484.txt:1339 | 7ef0449603189a7d7f18026972afe733d99b996d | CC0-1.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.