Skip to content

Wrong class seen from asyncio.create_datagram_endpoint #2292

@romuald

Description

@romuald

Summary

When using protocol instances returned from asyncio.create_datagram_endpoint, it seems like ty is guessing the wrong (parent's parent) class instead of the actual one being used

Here is a minimal example, (almost) copied from python documentation

import asyncio
from time import time

from typing import reveal_type


class EchoServerProtocol(asyncio.DatagramProtocol):
    start: float

    def connection_made(self, transport):
        self.transport = transport

    def datagram_received(self, data, addr):
        message = data.decode()
        print('Received %r from %s' % (message, addr))
        print('Send %r to %s' % (message, addr))
        self.transport.sendto(data, addr)

    def __init__(self):
        super().__init__()
        self.start = time()


async def main():
    print("Starting UDP server")

    loop = asyncio.get_event_loop()

    transport, protocol = await loop.create_datagram_endpoint(
        EchoServerProtocol,
        local_addr=('127.0.0.1', 9999))

    reveal_type(protocol)  # BaseProtocol instead of EchoServerProtocol

    print(protocol.start)

    try:
        await asyncio.sleep(3600)
    finally:
        transport.close()


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

When analysed, ty guesses the type of protocol as BaseProtocol (the parent class of DatagramProtocol), the error is error[unresolved-attribute]: Object of type BaseProtocolhas no attributestart``

The actual MRO at runtime is:

<class '__main__.EchoServerProtocol'>,
<class 'asyncio.protocols.DatagramProtocol'>,
<class 'asyncio.protocols.BaseProtocol'>,
<class 'object'>

Note that not inheriting from asyncio.DatagramProtocol will not raise an issue but the type will then be Unknown

Version

0.0.8

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions