[Python] Why does overriding a method with different async behavior cause subtle bugs in...

Discussão em 'Python' iniciado por Stack, Julho 20, 2025.

  1. Stack

    Stack Membro Participativo

    I recently ran into something weird while working with inheritance in Python. I had a base class method that was synchronous, but in the subclass, I accidentally overrode it as an async method (without realizing the base code expected it to be sync).

    Surprisingly, the code didn’t break immediately—it silently failed or acted unexpectedly later when that method was used in a context that wasn’t awaiting anything.

    Example:

    class Base:
    def process(self):
    print("Base processing...")

    class Child(Base):
    async def process(self):
    print("Child async processing...")

    obj = Child()
    obj.process()


    Output:

    RuntimeWarning: coroutine 'Child.process' was never awaited obj.process()
    RuntimeWarning: Enable tracemalloc to get the object allocation traceback


    I expected this to raise some obvious error, but it didn't. Instead, it just returned a coroutine object, and unless I explicitly awaited it, it wouldn't run.

    Why does Python allow this kind of override where method signatures (especially async vs sync) don’t match? Is there a clean or recommended way to catch this kind of mistake at runtime or during development?

    Continue reading...

Compartilhe esta Página