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
887 values
source
stringclasses
1 value
origin
stringclasses
887 values
origin_revision
stringclasses
1 value
license
stringclasses
1 value
train
3.11
exception-groups
654
3.11
modern
exception-groups/modern_13.py
try: raise BlockingIOError except* OSError as e: print(repr(e))
pydocs
pep-0654.rst:679
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
exception-groups
654
3.11
modern
exception-groups/modern_14.py
try: try: raise ValueError(12) except* TypeError as e: print('never') except ValueError as e: print(f'caught ValueError: {e!r}')
pydocs
pep-0654.rst:691
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
exception-groups
654
3.11
modern
exception-groups/modern_15.py
try: try: raise ExceptionGroup( "eg", [ ValueError(1), TypeError(2), OSError(3), ExceptionGroup( "nested", [OSError(4), TypeError(5), ValueError(6)]) ] ) ex...
pydocs
pep-0654.rst:753
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
exception-groups
654
3.11
modern
exception-groups/modern_16.py
try: raise ExceptionGroup( "eg", [ ValueError(1), TypeError(2), OSError(3), ExceptionGroup( "nested", [OSError(4), TypeError(5), ValueError(6)]) ] ) except* ValueError as e: print(f'*ValueError: {e!r}') ...
pydocs
pep-0654.rst:792
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
exception-groups
654
3.11
modern
exception-groups/modern_17.py
try: raise ExceptionGroup("one", [ValueError('a'), TypeError('b')]) except* ValueError: raise ExceptionGroup("two", [KeyError('x'), KeyError('y')])
pydocs
pep-0654.rst:854
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
exception-groups
654
3.11
modern
exception-groups/modern_18.py
try: raise TypeError('bad type') except* TypeError as e: raise ValueError('bad value') from e
pydocs
pep-0654.rst:897
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
exception-groups
654
3.11
modern
exception-groups/modern_19.py
try: raise TypeError(1) except* TypeError: raise ValueError(2) from None # <- not caught in the next clause except* ValueError: print('never')
pydocs
pep-0654.rst:922
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
exception-groups
654
3.11
modern
exception-groups/modern_20.py
try: raise ExceptionGroup("eg", [ValueError('a')]) except* ValueError: raise KeyError('x') try: raise ExceptionGroup("eg", [ValueError('a'), TypeError('b')]) except* ValueError: raise KeyError('x')
pydocs
pep-0654.rst:943
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
exception-groups
654
3.11
modern
exception-groups/modern_21.py
try: low_level_os_operation() except* OSError as errors: exc = errors.subgroup(lambda e: e.errno != errno.EPIPE) if exc is not None: raise exc from None
pydocs
pep-0654.rst:999
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
exception-groups
654
3.11
modern
exception-groups/modern_22.py
eg = ExceptionGroup("eg", [TypeError(12)]) eg.foo = 'foo' try: raise eg except* TypeError as e: e.foo = 'bar' # ^----------- ``e`` is an ephemeral object that might get # destroyed after the ``except*`` clause. eg.foo
pydocs
pep-0654.rst:1017
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
exception-groups
654
3.11
modern
exception-groups/modern_23.py
try: ... except ExceptionGroup: # <- This works pass try: ... except* ExceptionGroup: # <- Runtime error pass try: ... except* (TypeError, ExceptionGroup): # <- Runtime error pass
pydocs
pep-0654.rst:1052
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
exception-groups
654
3.11
modern
exception-groups/modern_24.py
try: async with asyncio.TaskGroup() as g: g.create_task(task1); g.create_task(task2) except* KeyError: ... # handling KeyError here is meaningless, there's # no context to do anything with it but to log it.
pydocs
pep-0654.rst:1304
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
exception-groups
654
3.11
modern
exception-groups/modern_25.py
try: try: ... except SomeError: ... # handle the naked exception except* SomeError: ... # handle the exception group
pydocs
pep-0654.rst:1346
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
exception-groups
654
3.11
modern
exception-groups/modern_26.py
try: async with trio.open_nursery() as nursery: # Make two concurrent calls to child() nursery.start_soon(child) nursery.start_soon(child) except* ValueError: pass
pydocs
pep-0654.rst:1399
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
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.rst:43
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
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.rst:66
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
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.rst:98
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
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.rst:126
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
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.rst:152
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
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.rst:188
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
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.rst:304
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
async-generators
525
3.6
modern
async-generators/modern_07.py
async def gen(): try: await asyncio.sleep(0.1) yield 'hello' except ZeroDivisionError: await asyncio.sleep(0.2) yield 'world' g = gen() v = await g.asend(None) print(v) # Will print 'hello' after # sleeping for 0.1 seconds. v = await g.ath...
pydocs
pep-0525.rst:324
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
async-generators
525
3.6
modern
async-generators/modern_08.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.rst:490
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
async-generators
525
3.6
modern
async-generators/modern_09.py
async def g1(): yield 1 yield 2 async def g2(): async for v in g1(): yield v
pydocs
pep-0525.rst:551
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
async-generators
525
3.6
modern
async-generators/modern_10.py
@async_context_manager async def ctx(): await open() try: yield finally: await close() async with ctx(): await ...
pydocs
pep-0525.rst:568
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
async-generators
525
3.6
modern
async-generators/modern_11.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.rst:597
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
context-vars
567
3.7
modern
context-vars/modern_01.py
# Declare a context variable 'var' with the default value 42. var = ContextVar('var', default=42)
pydocs
pep-0567.rst:147
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
context-vars
567
3.7
modern
context-vars/modern_02.py
ctx = contextvars.copy_context()
pydocs
pep-0567.rst:231
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
context-vars
567
3.7
modern
context-vars/modern_03.py
var = ContextVar('var') var.set('spam') def main(): # 'var' was set to 'spam' before # calling 'copy_context()' and 'ctx.run(main)', so: # var.get() == ctx[var] == 'spam' var.set('ham') # Now, after setting 'var' to 'ham': # var.get() == ctx[var] == 'ham' ctx = copy_context() # Any changes ...
pydocs
pep-0567.rst:241
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
context-vars
567
3.7
modern
context-vars/modern_04.py
ctx = contextvars.copy_context() # Print all context variables and their values in 'ctx': print(ctx.items()) # Print the value of 'some_variable' in context 'ctx': print(ctx[some_variable])
pydocs
pep-0567.rst:276
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
context-vars
567
3.7
modern
context-vars/modern_05.py
def call_soon(self, callback, *args, context=None): if context is None: context = contextvars.copy_context() # ... some time later context.run(callback, *args)
pydocs
pep-0567.rst:309
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
context-vars
567
3.7
modern
context-vars/modern_06.py
class Task: def __init__(self, coro): ... # Get the current context snapshot. self._context = contextvars.copy_context() self._loop.call_soon(self._step, context=self._context) def _step(self, exc=None): ... # Every advance of the wrapped coroutine is done in ...
pydocs
pep-0567.rst:320
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
context-vars
567
3.7
modern
context-vars/modern_07.py
var = ContextVar('var') ctx = copy_context() ctx[var] = 'value' print(ctx[var]) # Prints 'value' print(var.get()) # Raises a LookupError
pydocs
pep-0567.rst:708
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
context-vars
567
3.7
modern
context-vars/modern_08.py
ctx = copy_context() def func(): ctx[var] = 'value' # Contrary to the previous example, this would work # because 'func()' is running within 'ctx'. print(ctx[var]) print(var.get()) ctx.run(func)
pydocs
pep-0567.rst:718
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
context-vars
567
3.7
modern
context-vars/modern_09.py
# Framework: current_request: ContextVar[Request] = \ ContextVar('current_request') # Later, while handling an HTTP request: request: Request = current_request.get() # Work with the 'request' object: return request.method
pydocs
pep-0567.rst:752
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
context-vars
567
3.7
modern
context-vars/modern_10.py
# Framework: current_request: ContextVar[Optional[Request]] = \ ContextVar('current_request', initial_value=None) # Later, while handling an HTTP request: request: Optional[Request] = current_request.get() # Check if the current request object was set: if request is None: raise RuntimeError # Work with the ...
pydocs
pep-0567.rst:771
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
context-vars
567
3.7
legacy
context-vars/legacy_01.py
class PrecisionStorage(threading.local): # Subclass threading.local to specify a default value. value = 0.0 precision = PrecisionStorage() # To set a new precision: precision.value = 0.5 # To read the current precision: print(precision.value)
pydocs
pep-0567.rst:813
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
context-vars
567
3.7
modern
context-vars/modern_11.py
precision = contextvars.ContextVar('precision', default=0.0) # To set a new precision: precision.set(0.5) # To read the current precision: print(precision.get())
pydocs
pep-0567.rst:828
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
context-vars
567
3.7
modern
context-vars/modern_12.py
executor = ThreadPoolExecutor() current_context = contextvars.copy_context() executor.submit(current_context.run, some_function)
pydocs
pep-0567.rst:843
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
breakpoint
553
3.7
legacy
breakpoint/legacy_01.py
foo() import pdb; pdb.set_trace() bar()
pydocs
pep-0553.rst:27
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
breakpoint
553
3.7
modern
breakpoint/modern_01.py
foo() breakpoint() bar()
pydocs
pep-0553.rst:70
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
breakpoint
553
3.7
modern
breakpoint/modern_02.py
os.environ['PYTHONBREAKPOINT'] = 'foo.bar.baz' breakpoint() # Imports foo.bar and calls foo.bar.baz()
pydocs
pep-0553.rst:141
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
str-affix-removal
616
3.9
legacy
str-affix-removal/legacy_01.py
if test_func_name.startswith("test_"): print(test_func_name[5:]) else: print(test_func_name)
pydocs
pep-0616.rst:104
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
str-affix-removal
616
3.9
modern
str-affix-removal/modern_01.py
print(test_func_name.removeprefix("test_"))
pydocs
pep-0616.rst:111
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
str-affix-removal
616
3.9
legacy
str-affix-removal/legacy_02.py
if funcname.startswith("context."): self.funcname = funcname.replace("context.", "") self.contextfunc = True else: self.funcname = funcname self.contextfunc = False
pydocs
pep-0616.rst:123
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
str-affix-removal
616
3.9
modern
str-affix-removal/modern_02.py
if funcname.startswith("context."): self.funcname = funcname.removeprefix("context.") self.contextfunc = True else: self.funcname = funcname self.contextfunc = False
pydocs
pep-0616.rst:132
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
str-affix-removal
616
3.9
modern
str-affix-removal/modern_03.py
self.contextfunc = funcname.startswith("context.") self.funcname = funcname.removeprefix("context.")
pydocs
pep-0616.rst:141
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
str-affix-removal
616
3.9
legacy
str-affix-removal/legacy_03.py
def strip_quotes(text): if text.startswith('"'): text = text[1:] if text.endswith('"'): text = text[:-1] return text
pydocs
pep-0616.rst:150
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
str-affix-removal
616
3.9
modern
str-affix-removal/modern_04.py
def strip_quotes(text): return text.removeprefix('"').removesuffix('"')
pydocs
pep-0616.rst:159
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
str-affix-removal
616
3.9
legacy
str-affix-removal/legacy_04.py
creationDate = header['POT-Creation-Date'] # peel off the escaped newline at the end of string if creationDate.endswith('\\n'): creationDate = creationDate[:-len('\\n')]
pydocs
pep-0616.rst:168
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
str-affix-removal
616
3.9
modern
str-affix-removal/modern_05.py
creationDate = header['POT-Creation-Date'].removesuffix('\\n')
pydocs
pep-0616.rst:176
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
str-affix-removal
616
3.9
modern
str-affix-removal/modern_06.py
s = 'Foo' * 100 + 'Bar' prefix = 'Foo' while s.startswith(prefix): s = s.removeprefix(prefix) s
pydocs
pep-0616.rst:205
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
exception-notes
678
3.11
modern
exception-notes/modern_01.py
try: raise TypeError('bad type') except Exception as e: e.add_note('Add some information') raise
pydocs
pep-0678.rst:67
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
exception-notes
678
3.11
modern
exception-notes/modern_02.py
@contextlib.contextmanager def add_exc_note(note: str): try: yield except Exception as err: err.add_note(note) raise with add_exc_note(f"While attempting to frobnicate {item=}"): frobnicate_or_raise(item)
pydocs
pep-0678.rst:325
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
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.rst:66
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
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.rst:107
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
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.rst:194
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
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.rst:213
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
modern
dataclasses/modern_01.py
@dataclass class InventoryItem: '''Class for keeping track of an item in inventory.''' name: str unit_price: float quantity_on_hand: int = 0 def total_cost(self) -> float: return self.unit_price * self.quantity_on_hand
pydocs
pep-0557.rst:42
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
legacy
dataclasses/legacy_01.py
def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0) -> None: self.name = name self.unit_price = unit_price self.quantity_on_hand = quantity_on_hand def __repr__(self): return f'InventoryItem(name={self.name!r}, unit_price={self.unit_price!r}, quantity_on_hand={self.quantity_on_ha...
pydocs
pep-0557.rst:55
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
modern
dataclasses/modern_02.py
@dataclass class C: ... @dataclass() class C: ... @dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False) class C: ...
pydocs
pep-0557.rst:176
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
modern
dataclasses/modern_03.py
@dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'
pydocs
pep-0557.rst:265
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
modern
dataclasses/modern_04.py
@dataclass class C: x: int y: int = field(repr=False) z: int = field(repr=False, default=10) t: int = 20
pydocs
pep-0557.rst:342
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
modern
dataclasses/modern_05.py
@dataclass class C: a: float b: float c: float = field(init=False) def __post_init__(self): self.c = self.a + self.b
pydocs
pep-0557.rst:383
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
modern
dataclasses/modern_06.py
@dataclass class C: i: int j: int = None database: InitVar[DatabaseType] = None def __post_init__(self, database): if self.j is None and database is not None: self.j = database.lookup('j') c = C(10, database=my_database)
pydocs
pep-0557.rst:423
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
modern
dataclasses/modern_07.py
@dataclass class Base: x: Any = 15.0 y: int = 0 @dataclass class C(Base): z: int = 10 x: int = 15
pydocs
pep-0557.rst:464
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
modern
dataclasses/modern_08.py
@dataclass class D: x: List = [] def add(self, element): self.x += element
pydocs
pep-0557.rst:519
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
modern
dataclasses/modern_09.py
@dataclass class D: x: list = field(default_factory=list) assert D().x is not D().x
pydocs
pep-0557.rst:550
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
modern
dataclasses/modern_10.py
@dataclass class Point: x: int y: int @dataclass class C: l: List[Point] p = Point(10, 20) assert asdict(p) == {'x': 10, 'y': 20} c = C([Point(0, 0), Point(10, 4)]) assert asdict(c) == {'l': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
pydocs
pep-0557.rst:571
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
modern
dataclasses/modern_11.py
C = make_dataclass('C', [('x', int), 'y', ('z', int, field(default=5))], namespace={'add_one': lambda self: self.x + 1})
pydocs
pep-0557.rst:613
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
modern
dataclasses/modern_12.py
@dataclass class C: x: int y: 'typing.Any' z: int = 5 def add_one(self): return self.x + 1
pydocs
pep-0557.rst:621
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
legacy
dataclasses/legacy_02.py
Time = namedtuple('Time', ['hour', 'minute']) def get_time(): return Time(12, 0)
pydocs
pep-0557.rst:710
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
modern
dataclasses/modern_13.py
@dataclass class C: x: int @classmethod def from_file(cls, filename): with open(filename) as fl: file_value = int(fl.read()) return C(file_value) c = C.from_file('file.txt')
pydocs
pep-0557.rst:762
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
modern
dataclasses/modern_14.py
@dataclass class Square: length: float area: float = field(init=False, default=0.0) def __post_init__(self): self.area = self.length * self.length s1 = Square(1.0) s2 = replace(s1, length=2.0)
pydocs
pep-0557.rst:831
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
modern
dataclasses/modern_15.py
@dataclass(init=False) class ArgHolder: args: List[Any] kwargs: Mapping[Any, Any] def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs a = ArgHolder(1, 2, three=3)
pydocs
pep-0557.rst:867
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
legacy
dataclasses/legacy_03.py
class Application: def __init__(self, name, requirements, constraints=None, path='', executable_links=None, executables_dir=()): self.name = name self.requirements = requirements self.constraints = {} if constraints is None else constraints self.path = path self.executable_li...
pydocs
pep-0557.rst:883
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
dataclasses
557
3.7
modern
dataclasses/modern_16.py
@dataclass class Application: name: str requirements: List[Requirement] constraints: Dict[str, str] = field(default_factory=dict) path: str = '' executable_links: List[str] = field(default_factory=list) executable_dir: Tuple[str] = () additional_items: List[str] = field(init=False, default_f...
pydocs
pep-0557.rst:898
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
zoneinfo
615
3.9
modern
zoneinfo/modern_01.py
a = ZoneInfo(key) b = ZoneInfo(key) assert a is b
pydocs
pep-0615.rst:108
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
zoneinfo
615
3.9
modern
zoneinfo/modern_02.py
a = ZoneInfo.no_cache(key) b = ZoneInfo(key) a is not b
pydocs
pep-0615.rst:152
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
zoneinfo
615
3.9
modern
zoneinfo/modern_03.py
NYC0 = ZoneInfo("America/New_York") NYC0 is ZoneInfo("America/New_York") ZoneInfo.clear_cache() NYC1 = ZoneInfo("America/New_York") NYC0 is NYC1 NYC1 is ZoneInfo("America/New_York")
pydocs
pep-0615.rst:219
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
zoneinfo
615
3.9
modern
zoneinfo/modern_04.py
NYC0 = ZoneInfo("America/New_York") LA0 = ZoneInfo("America/Los_Angeles") ZoneInfo.clear_cache(only_keys=["America/New_York"]) NYC1 = ZoneInfo("America/New_York") LA0 = ZoneInfo("America/Los_Angeles") NYC0 is NYC1 LA0 is LA1
pydocs
pep-0615.rst:234
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
zoneinfo
615
3.9
modern
zoneinfo/modern_05.py
zone = ZoneInfo("Pacific/Kwajalein") str(zone) dt = datetime(2020, 4, 1, 3, 15, tzinfo=zone) f"{dt.isoformat()} [{dt.tzinfo}]"
pydocs
pep-0615.rst:263
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
zoneinfo
615
3.9
modern
zoneinfo/modern_06.py
zone = ZoneInfo.from_file(f) str(zone)
pydocs
pep-0615.rst:275
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
zoneinfo
615
3.9
modern
zoneinfo/modern_07.py
a = ZoneInfo("Europe/Berlin") b = pickle.loads(europe_berlin_pkl) a is b
pydocs
pep-0615.rst:310
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
zoneinfo
615
3.9
modern
zoneinfo/modern_08.py
a = ZoneInfo("Europe/Berlin") b = pickle.loads(europe_berlin_pkl_nc) a is b
pydocs
pep-0615.rst:324
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
zoneinfo
615
3.9
modern
zoneinfo/modern_09.py
reset_tzpath(to=["/my/custom/tzdb"]) a = ZoneInfo("My/Custom/Zone") reset_tzpath() b = ZoneInfo("My/Custom/Zone") del a del b c = ZoneInfo("My/Custom/Zone")
pydocs
pep-0615.rst:534
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.11
explicit-encoding
597
3.10
modern
explicit-encoding/modern_01.py
def read_text(self, encoding=None, errors=None): encoding = io.text_encoding(encoding) with self.open(mode='r', encoding=encoding, errors=errors) as f: return f.read()
pydocs
pep-0597.rst:174
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.12
type-hints
484
3.5
modern
type-hints/modern_01.py
def greeting(name: str) -> str: return 'Hello ' + name
pydocs
pep-0484.rst:35
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.12
type-hints
484
3.5
modern
type-hints/modern_02.py
Url = str def retry(url: Url, retry_count: int) -> None: ...
pydocs
pep-0484.rst:201
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.12
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.rst:213
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.12
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.rst:227
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.12
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.rst:245
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.12
type-hints
484
3.5
modern
type-hints/modern_06.py
def partial(func: Callable[..., str], *args) -> Callable[..., str]: ... # Body
pydocs
pep-0484.rst:258
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.12
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.rst:285
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.12
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.rst:292
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.12
type-hints
484
3.5
modern
type-hints/modern_09.py
from typing import TypeVar, Text AnyStr = TypeVar('AnyStr', Text, bytes) def concat(x: AnyStr, y: AnyStr) -> AnyStr: return x + y
pydocs
pep-0484.rst:313
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.12
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.rst:342
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.12
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.rst:355
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.12
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.rst:384
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0
train
3.12
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.rst:467
e449c7e446faec3ecf953e83fbe677b771bf5d7c
CC0-1.0