-
First of all, thanks for svcs, especially the great documentation that outlines the related concepts so clearly! My question is, what is the best way to handle multiple dependencies that have the same type? Say, you need The only way to do this right now as far as I can see is to create empty subclasses of the service in order to distinguish between them: import sqlalchemy as sa
class PrimaryConnection(sa.Connection):
pass
class SecondaryConnection(sa.Connection):
pass
registry.register_factory(PrimaryConnection, get_conn_for_primary)
registry.register_factory(SecondaryConnection, get_conn_for_secondary) Now this works fine, except for the fact that what you get back from the container when asking for One idea that I had is that svcs could support registering services with a key of registry.register_factory((sa.Connection, "primary"), get_conn_for_primary)
registry.register_factory((sa.Connection, "secondary"), get_conn_for_secondary)
# later ...
primary, secondary = container.get((sa.Connection, "primary"), (sa.Connection, "secondary")) This also works already, because I guess the types you pass at registration are just used as dictionary keys. It does not typecheck of course, but it could be made to do so with additional overloads of It's entirely possible that I missed something and there is already a better way to do this. If so I think this would be a good addition to the documentation. Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
It just occurred to me that there's a third way, using from typing import Annotated, TypeAlias
PrimaryConnection: TypeAlias = Annotated[sa.Connection, "primary"]
SecondaryConnection: TypeAlias = Annotated[sa.Connection, "secondary"] This checks all the boxes: no unnecessary subclasses, type-safe, no changes to svcs required. |
Beta Was this translation helpful? Give feedback.
Ohhh that’s interesting! I was gonna say the obvious way would you introduce something like a context that would become a second element in the lookup tuple, but your annotated solution is so much more Modern-Typing-Pythonic! I, too, keep forgetting about it – this needs to be documented! :)