
Una nueva selección de consejos y programación de Python de mi feed @pythonetc.
←
Publicaciones anterioresObviamente, diferentes tareas de
asyncio
usan diferentes pilas. Puede verlos todos en cualquier momento recibiendo con
asyncio.all_tasks()
todas las tareas que se están realizando actualmente, y usando
task.get_stack()
recibir pilas para todas las tareas.
import linecache import asyncio import random async def producer(queue): while True: await queue.put(random.random()) await asyncio.sleep(0.01) async def avg_printer(queue): total = 0 cnt = 0 while True: while queue.qsize(): x = await queue.get() total += x cnt += 1 queue.task_done() print(total / cnt) await asyncio.sleep(1) async def monitor(): while True: await asyncio.sleep(1.9) for task in asyncio.all_tasks(): if task is not asyncio.current_task(): f = task.get_stack()[-1] last_line = linecache.getline( f.f_code.co_filename, f.f_lineno, f.f_globals, ) print(task) print('\t', last_line.strip()) print() async def main(): loop = asyncio.get_event_loop() queue = asyncio.Queue() loop.create_task(producer(queue)) loop.create_task(producer(queue)) loop.create_task(producer(queue)) loop.create_task(avg_printer(queue)) loop.create_task(monitor()) loop = asyncio.get_event_loop() loop.create_task(main()) loop.run_forever()
Para no sufrir directamente con el objeto de pila y no usar el módulo
linecache
, puede llamar a
task.print_stack()
.
Usando el método de
translate
de
str
puede convertir o eliminar caracteres en una cadena (como lo hace la utilidad
tr
):
>>> 'Hello, world!'.translate({ ... ord(','): ';', ... ord('o'): '0', ... }) 'Hell0; w0rld!'
El único argumento para
translate
es un diccionario en el que los códigos de caracteres se asignan a caracteres (o códigos). Por lo general, es más conveniente componer dicho diccionario utilizando el método estático
str.maketrans
:
>>> 'Hello, world!'.translate(str.maketrans({ ... ',': ';', ... 'o': '0', ... })) 'Hell0; w0rld!'
O incluso:
>>> 'Hello, world!'.translate(str.maketrans( ... ',o', ';0' ... )) 'Hell0; w0rld!'
El tercer argumento es eliminar caracteres:
>>> tr = str.maketrans(',o', ';0', '!') >>> tr {44: 59, 111: 48, 33: None} >>> 'Hello, world!'.translate(tr) 'Hell0; w0rld'
mypy
aún no admite definiciones de tipo recursivas:
from typing import Optional, Dict from pathlib import Path TreeDict = Dict[str, 'TreeDict'] def tree(path: Path) -> TreeDict: return { f.name: tree(f) if f.is_dir() else None for f in path.iterdir() }
Recibirá un mensaje de error:
Cannot resolve name "TreeDict" (possible cyclic definition)
.
Puedes seguir la situación aquí:
https://github.com/python/mypy/issues/731Para que una función regular se vuelva recursiva, es suficiente llamarse a sí misma. Pero las cosas no son tan simples con los generadores: la mayoría de las veces necesita usar el
yield from
de los generadores recursivos:
from operator import itemgetter tree = { 'imgs': { '1.png': None, '2.png': None, 'photos': { 'me.jpg': None }, }, 'MANIFEST': None, } def flatten_tree(tree): for name, children in sorted( tree.items(), key=itemgetter(0) ): yield name if children: yield from flatten_tree(children) print(list(flatten_tree(tree)))
Puede usar no solo con variables, sino con cualquier expresión en general. Se calcula en cada iteración:
>>> log2 = {} >>> key = 1 >>> for log2[key] in range(100): ... key *= 2 ... >>> log2[16] 4 >>> log2[1024] 10