python-injector / python-injector/injector

[question] string-based annotations? equivalent to guice Names.named() and @Named

Open
#133 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
1.5k
Forks
94
PR merge metrics
No merged PRs in 30d

Description

I know it's generally better to use static annotations (eg https://github.com/alecthomas/injector/issues/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 injector import Module, Injector, Binder, inject
from dataclasses import dataclass
from collections import defaultdict


def named(name: str, *, seen=defaultdict(lambda: type("", (), {}))):
    return seen[name]


@inject
@dataclass
class MyClass:
    myval: named("mine")
    myotherval: named("somethingelse")


def conf(binder: Binder):
    binder.bind(named("mine"), to="test1")
    binder.bind(named("somethingelse"), to="test2")


myclass: MyClass = Injector([conf]).get(MyClass)
print(myclass.myval)
print(myclass.myotherval)

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.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the Injector and Binder entry points shown in the example, and check how annotated constructor parameters are resolved. Compare that path with Guice's Names.named and @Named use case to determine whether the package already supports string-qualified bindings. Done means a documented answer or a scoped decision on whether this feature should be added.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.