Hadron / carthage

Carthage is an Infrastructure as Code (IAC) framework
Other
7 stars 4 forks source link

Injector.filter allows `predicate` to be None but attempts to call it regardless #74

Closed srak289 closed 1 month ago

srak289 commented 1 month ago
from carthage.dependency_injection import *

inj = Injector()
inj.claim("foo")

class Bar:
    def __init__(self, **kwargs):
        pass

a = Bar(name="spam")

inj.add_provider(InjectionKey(Bar), a)

inj.filter(Bar)

# Traceback (most recent call last):
#   File "/home/srak/projects/carthage/test.py", line 14, in <module>
#     inj.filter(Bar)
#   File "/home/srak/projects/carthage/carthage/dependency_injection/base.py", line 431, in filter
#     result.update({k: True for k in self._providers.keys() if ((not target) or   k.target is target ) and predicate(k)})
#                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#   File "/home/srak/projects/carthage/carthage/dependency_injection/base.py", line 431, in <dictcomp>
#     result.update({k: True for k in self._providers.keys() if ((not target) or   k.target is target ) and predicate(k)})
#                                                                                                           ^^^^^^^^^^^^
# TypeError: 'NoneType' object is not callable

In the case where predicate is not passed to Injector.filter() this function fails.

I suggest either adding something like:

if isinstance(predicate, type(None)):
    predicate = lambda x: True

Or making predicate a required argument.