[New-bugs-announce] [issue38817] Immutable types inplace operations work incorrect in async

Антон Брызгалов report at bugs.python.org
Fri Nov 15 14:56:48 EST 2019


New submission from Антон Брызгалов <tony.bryzgaloff at gmail.com>:

Example code (also is attached to the issue):


import asyncio

async def count_smth(seconds: int) -> int:
    await asyncio.sleep(seconds)
    return seconds * 3

async def small_job(d: dict, key: str, seconds: int) -> None:
    d[key] += await count_smth(seconds)  # <-- strange happens here

async def main() -> None:
     d = dict(key=0)
     await asyncio.gather(
           small_job(d, 'key', 1),
           small_job(d, 'key', 2),
     )
     print(d['key'])  # expected: 0 + 1 * 3 + 2 * 3 = 9, actual: 6

if __name__ == '__main__':
    asyncio.run(main())


Expected output: 0 + 1 * 3 + 2 * 3 = 9. Actual: 6. Seems to be a race condition.

Same happens for other immutable types: str, tuple (when used as values of dict instead of int). But works correctly with list and custom class with __iadd__ method.

----------
components: Interpreter Core, asyncio
files: scratch_1.py
messages: 356710
nosy: asvetlov, yselivanov, Антон Брызгалов
priority: normal
severity: normal
status: open
title: Immutable types inplace operations work incorrect in async
type: behavior
versions: Python 3.6, Python 3.7
Added file: https://bugs.python.org/file48717/scratch_1.py

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue38817>
_______________________________________


More information about the New-bugs-announce mailing list