Home Blog CV Projects Patterns Notes Book Colophon Search

Python Protocol Attributes

25 Jun, 2024

I hadn't realised that Protocol can be checked by mypy for attributes as well as methods.

Here's a starting point for experimenting with:

from typing import Protocol, Any
import asyncio

class MyProtocol(Protocol):
    data: Any

    @classmethod
    async def create(cls) -> 'MyProtocol':
        ...

class MyClass:
    def __init__(self, data: Any):
        self.data = data

    @classmethod
    async def create(cls) -> 'MyClass':
        # Perform asynchronous initialization here
        data = await cls.fetch_data()
        return cls(data)

    @staticmethod
    async def fetch_data() -> Any:
        # Simulate an async data fetching operation
        await asyncio.sleep(0.1)
        return "some data"

# Ensure MyClass conforms to MyProtocol
def use_myclass_protocol(obj: MyProtocol) -> None:
    pass

# Usage
async def main() -> None:
    my_instance: MyProtocol = await MyClass.create()  # This should pass type checking
    use_myclass_protocol(my_instance)
    print(my_instance.data)

asyncio.run(main())

And its usage:

$ mypy protocol.py --strict
Success: no issues found in 1 source file
$ python3 protocol.py 
some data

Comments

Be the first to comment.

Add Comment





Copyright James Gardner 1996-2020 All Rights Reserved. Admin.