Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable use of annotated types #180

Open
wants to merge 20 commits into
base: master
Choose a base branch
from

Conversation

neilmacintyre
Copy link

@neilmacintyre neilmacintyre commented Mar 20, 2024

Changing to draft. This breaks backwards compatibility in cases where Annotated types are used for reasons other than punq resolutions. This is probably best solved by adding a flag in the annotations to indicate that they are for punq and falling back to the type in the annotated type if the flag is missing

Allows types to be register as annotated types to to allow for disambiguating between common types.

An example of this in use (previously the annotation part of the type was scrubbed before registering):

from typing import Annotated, Generic, Type, TypeVar

import punq

container = punq.Container()


T = TypeVar('T')

class Subscriber(Generic[T]):
    def __init__(self, msg_type: Type[T], topic: str):
        self.msg_type = msg_type
        self.topic = topic

class Test:
    def __init__(
        self,
        temp_sub: Annotated[Subscriber[float], '/topic/temp'],
        dist_sub: Annotated[Subscriber[float], '/topic/dist'],
    ):
        self.temp_sub = temp_sub
        self.dist_sub = dist_sub

    def print_topic_names(self) -> None:
        print(self.temp_sub.topic)
        print(self.dist_sub.topic)


if __name__ == '__main__':
    temp_sub = Subscriber(float, '/topic/temp')
    container.register(Annotated[Subscriber[float], 'punq::/topic/temp'], instance=temp_sub)

    dist_sub = Subscriber(float, '/topic/dist')
    container.register(Annotated[Subscriber[float], 'punq::/topic/dist'], instance=dist_sub)

    container.register(Test)
    test = container.resolve(Test)
    test.print_topic_names()
    print(test.temp_sub.topic)
    print(test.dist_sub.topic)

@neilmacintyre neilmacintyre marked this pull request as draft March 21, 2024 13:18
@neilmacintyre neilmacintyre marked this pull request as ready for review June 24, 2024 17:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant