Skip to content

weakref.finalize is not called if exception occurs inside asyncio.wait_for #104467

Closed as not planned
@Klayflash

Description

@Klayflash

CPython python-3.11.3 (windows and linux)

Must "MyClass onFinalize" be called before "main end"?

There are bad and good cases.
Should be a difference between bad and good cases from "onFinalize" call time perspective?

The code that reproduces 2 good and 3 bad cases is below:

import asyncio
import weakref
import traceback

class MyClass:
    def __init__(self):
        print("MyClass __init__")
        weakref.finalize(self,MyClass.onFinalize)
    
    @classmethod
    def onFinalize(cls):
        print("MyClass onFinalize")

async def raiseException():
    print("raiseException sleeping")
    await asyncio.sleep(2)
    print("raiseException raising")
    raise Exception("Test exception")

async def someFunct():
    print("someFunct 1")
    myObj = MyClass()

    ############
    # case 1 (good)
    await raiseException()

    ############
    # case 2 (bad)
    #print("someFunct asyncio.wait_for")
    #await asyncio.wait_for(raiseException(),3600)

    ############
    # case 3 (bad)
    #print("someFunct creating task")
    #task = asyncio.Task(raiseException())
    #print("someFunct await task")
    #await task

    ############
    # case 4 (good)
    #print("someFunct creating task")
    #task = asyncio.Task(raiseException())
    #print("someFunct asyncio.wait")
    #done, pending = await asyncio.wait([task],return_when=asyncio.FIRST_EXCEPTION)

    ############
    # case 5 (bad)
    #print("someFunct gather")
    #await asyncio.gather(raiseException())

    ######
    print("someFunct end")

async def main():
    print("main 1")

    try:
        await someFunct()
        print("main someFunct returned without exception")
    except:
        print("main except exception={}".format(traceback.format_exc()))

    print("main end")


asyncio.run(main())

Metadata

Metadata

Assignees

No one assigned

    Labels

    pendingThe issue will be closed if no feedback is providedtopic-asynciotype-bugAn unexpected behavior, bug, or error

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions