Библиотека Python разработчика. Книги по программированию на Python.
for and with can be asynchronous. async with uses __aenter__ and __aexit__ magic methods, async for uses __aiter__ and __anext__. All of them are async and you can await within them:
import asyncio
class Sleep:
def __init__(self, t):
self._t = t
async def __aenter__(self):
await asyncio.sleep(self._t / 2)
async def __aexit__(self, *args):
await asyncio.sleep(self._t / 2)
async def main():
async with Sleep(2):
print('*')
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
When you implement __iter__ you often don't write an iterator with __next__ method, you just use yield that makes __iter__ a generator:
class Bracketed:
def __init__(self, data):
self._data = data
def __iter__(self):
for x in self._data:
yield '({})'.format(x)
print(list(Bracketed([1, 2, 3])))
# ['(1)', '(2)', '(3)']
PEP 525 allows you do the same with __aiter__. Both yield and await in the function body make it asynchronous generator. While await is used to communicate with the loop, yield deals with for:
import asyncio
class Slow:
def __init__(self, data, t=1):
self._data = data
self._t = t
async def __aiter__(self):
for x in self._data:
await asyncio.sleep(self._t)
yield x
async def main():
async for x in Slow([1, 2, 3]):
print(x)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())abs() - возвращает модуль переданного параметра.
all() - функция возвращает значение True, если все элементы в итерируемом объекте - истинны. В противном случае, она возвращает значение False.
any() - функция возвращает True, если какой-либо (любой) элемент в итерируемом объекте является истинным True. В противном случае, any() возвращает значение False.
ascii() - возвращает строку, содержащую печатное представление объекта, и экранирует символы, отличные от ASCII, в строке с помощью экранирования \ x, \ u или \ U.
bin() - функция преобразует целое число в двоичную строку с префиксом 0b.
Подписывайтесь на канал 👉@pythonofffthreading module gets you covered, it provides the threading.local() object that is thread-safe. Store there any data by simply accessing attributes: threading.local().symbol = '@'.
Still, both of that approaches are concurrency-unsafe meaning they won't work for coroutine call-chain where functions are not only called but can be awaited too. Once a coroutine does await, an event loop may run a completely different coroutine from a completely different chain. That won't work:
import asyncio
import sys
global_symbol = '.'
async def indication(timeout):
while True:
print(global_symbol, end='')
sys.stdout.flush()
await asyncio.sleep(timeout)
async def sleep(t, indication_t, symbol='.'):
loop = asyncio.get_event_loop()
global global_symbol
global_symbol = symbol
loop.create_task(indication(indication_t))
await asyncio.sleep(t)
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(
sleep(1, 0.1, '0'),
sleep(1, 0.1, 'a'),
sleep(1, 0.1, 'b'),
sleep(1, 0.1, 'c'),
))
You can fix that by having the loop set and restore the context every time it resumes some coroutine. The aiotask_context module does exactly this by changing the way how tasks are created with loop.set_task_factory. This works:
import asyncio
import sys
import aiotask_context as context
async def indication(timeout):
while True:
print(context.get('symbol'), end='')
sys.stdout.flush()
await asyncio.sleep(timeout)
async def sleep(t, indication_t, symbol='.'):
loop = asyncio.get_event_loop()
context.set(key='symbol', value=symbol)
loop.create_task(indication(indication_t))
await asyncio.sleep(t)
loop = asyncio.get_event_loop()
loop.set_task_factory(context.task_factory)
loop.run_until_complete(asyncio.gather(
sleep(1, 0.1, '0'),
sleep(1, 0.1, 'a'),
sleep(1, 0.1, 'b'),
sleep(1, 0.1, 'c'),
))In : format(0.1, '.17f')
Out: '0.10000000000000001'
The decimal module lets you use decimal floating point arithmetic with arbitrary precision:
In : Decimal(1) / Decimal(3)
Out: Decimal('0.3333333333333333333333333333')
That's still can be not enough:
In [61]: Decimal(1) / Decimal(3) * Decimal(3) == Decimal(1)
Out[61]: False
For perfect computations, you can use fractions, that stores any number as a rational one:
In : Fraction(1) / Fraction(3) * Fraction(3) == Fraction(1)
Out: True
The obvious limitation is you still have to use approximations to irrational numbers (such as π).tempfile module can help you to achieve that.
Since temporary stuff usually should be removed after use, tempfile provides context manager as well as plain functions:
with tempfile.TemporaryDirectory() as dir_path:
open(os.path.join(dir_path, 'a'), 'w').close()
open(os.path.join(dir_path, 'b'), 'w').close()
open(os.path.join(dir_path, 'c'), 'w').close()
assert files_of(dir_path) == ['a', 'b', 'c']float('infinity') или float('inf') для получения максимально возможного числа
float('-infinity') или float('-inf') для получения минимально возможного числа.
Не работает с int, требуется использовать именно float.
Подписывайтесь на канал 👉@pythonofff