Skip to content

@Named annotation support #56

Closed
Closed

Description

@tadas-subonis

Is there a possibility to do something like @nAmed("myQualifier") in Java ( http://docs.oracle.com/javaee/6/api/javax/inject/Named.html ) using this framework?

Thanks

Activity

  1. alecthomas commented on Oct 24, 2016

    @alecthomas
    Collaborator

    Yes, this is possible.

  2. tadas-subonis commented on Oct 25, 2016

    @tadas-subonis
    Author

    Thanks

    On Mon, Oct 24, 2016 at 2:08 AM, Alec Thomas [email protected]
    wrote:

    Closed #56 #56.

    —
    You are receiving this because you authored the thread.
    Reply to this email directly, view it on GitHub
    #56 (comment), or mute
    the thread
    https://github.com/notifications/unsubscribe-auth/AAPFsrmypCowwmFYzsz7V2QRbI6BP1rEks5q2_cDgaJpZM4KWrMs
    .

    Kind Regards,
    Tadas Šubonis

  3. jstasiak commented on Feb 9, 2017

    @jstasiak
    Collaborator

    I'll leave this here for historical visibility - subclassing is another way to achieve what you want:

    from injector import Binder, inject, Injector
    
    
    class Seat:
        def __init__(self, data: str) -> None:
            self.data = data
    
        def __repr__(self) -> str:
            return 'Seat(%r)' % (self.data,)
    
    
    class DriverSeat(Seat):
        pass
    
    
    class PassengerSeat(Seat):
        pass
    
    
    class Car:
        @inject
        def __init__(self, driver_seat: DriverSeat, passenger_seat: PassengerSeat) -> None:
            self.driver_seat = driver_seat
            self.passenger_seat = passenger_seat
    
    
    def configure(binder: Binder) -> None:
        binder.bind(DriverSeat, to=DriverSeat('fancy driver seat'))
        binder.bind(PassengerSeat, to=PassengerSeat('crude passenger seat'))
    
    
    injector = Injector([configure])
    car = injector.get(Car)
    print(car.driver_seat)

    Result:

    Seat('fancy driver seat')
    

    Not everyone needs to like this solution (it's a bit hacky) but it works and once Injector gets some type hints it'll be more static analysis friendly than using Key.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions