kodemore / kink

Dependency injection container made for Python
MIT License
397 stars 25 forks source link

Registering a service with value `None` will trigger ServiceError("Service ... is not regisitered") on access #37

Closed roytseng-tw closed 1 year ago

roytseng-tw commented 1 year ago

Reproduce

from kink import di

di['a'] = None
di['a']  # <-- Raise Service Error

Reason

Object None is used to tell if a service is registered or not. This is why a service registered with the value None is treated as not registered. Container.__getitem__ https://github.com/kodemore/kink/blob/master/kink/container.py#L34-L35 https://github.com/kodemore/kink/blob/master/kink/container.py#L40-L41 Container._get https://github.com/kodemore/kink/blob/master/kink/container.py#L55-L56

Proposal

Define another sentinel object for this purpose.

MISSING = object()

# in `Container.__getitem__`
if service is not MISSING:
    return service

# in `Container._get`
if key not in self._services:
    return MISSING
dkraczkowski commented 1 year ago

@roytseng-tw Fixed in https://github.com/kodemore/kink/pull/39