You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[question] string-based annotations? equivalent to guice Names.named() and @Named #133
I know it's generally better to use static annotations (eg #69), but I found @Named annotations very useful in guice for configuration injection. I'm able to reproduce this feature using type but did I miss an existing implementation in the package? didn't want to reinvent the wheel, even if its only two lines of code.
From here I'd write a module that parses a config file and does binder.bind(named(key),to=value) to make it easy for classes to get values from the config to an injected class.
Granted, the types/aliases/names still need to be declared statically up front. If you want to be completely dynamic in config reading I think your other best choice is to have provider methods that receive configuration and construct your classes:
@jstasiak, just a nit-pick. technically NewType isn't a type alias, it creates a new, distinct type https://docs.python.org/3/library/typing.html#newtype. It's what meta-classes sometimes use under the hood and it's roughly equivalent to what defining a class does under the hood
The following are roughly equivalent (including how it sets the parent class pointer)
Activity
jstasiak commentedon Jan 22, 2020
No, you're right, something like this is not supported at the moment.
The closest you can get right now is with type aliases I think:
Granted, the types/aliases/names still need to be declared statically up front. If you want to be completely dynamic in config reading I think your other best choice is to have provider methods that receive configuration and construct your classes:
In both of those cases you don't lose type safety if you use any linters that test it, so there's that. :)
Injector has initial support for PEP 593 -- Flexible function and variable annotations so something like Guice's
@Namedcould be implemented now, just no one did it yet.jstasiak commentedon Jan 5, 2021
See #174 for a potential (not supported at the moment) way to use
Annotatedto achieve this.strangemonad commentedon Mar 22, 2023
@jstasiak, just a nit-pick. technically
NewTypeisn't a type alias, it creates a new, distinct type https://docs.python.org/3/library/typing.html#newtype. It's what meta-classes sometimes use under the hood and it's roughly equivalent to what defining a class does under the hoodThe following are roughly equivalent (including how it sets the parent class pointer)
A type alias would be defined as
Mine = strhttps://docs.python.org/3/library/typing.html#type-aliases