ivankorobkov / python-inject

Python dependency injection
Apache License 2.0
672 stars 77 forks source link

Add an argument for disabling runtime binding #24

Closed o-fedorov closed 5 years ago

o-fedorov commented 5 years ago

This addresses the issue #23

ivankorobkov commented 5 years ago

Hi!

If a user forgets to bind a class to an instance, in the best case she gets an exception like TypeError for abstract classes, typing variables, callables that require at least one argument and so on. Such messages are usually not helpful and sometimes obscuring.

One can see DI from two different point of views: 1) DI allows to automatically instantiate a graph of interdependent service instances, which are a program. 2) DI allows to dynamically structure a program via late-binding of its dependencies.

I'm in favor of the first. Imagine a Twitter-like application:


class Config:
    def __init__(self, dbconn=''):
        self.dbconn = dbconn

class Db:
    @inject.autoparams()
    def __init__(self, config: Config):
        pass

class Users:
    @inject.autoparams()
    def __init__(self, db: Db):
        pass

class Tweets:
    @inject.autoparams()
    def __init__(self, db: Db, users: Users):
        pass

class WsgiServer:
    @inject.autoparams()
    def __init__(self, tweets: Tweets, users: Users):
        pass    

In this case all dependencies are already specified. We only need to instantiate a graph of services with a custom Config:


def main():
    config = Config.read_yaml("config.yaml")
    inject.configure(lambda binder: binder.bind(Config, config))

    # That's all!

However, if you really need to prevent injector from automatically instantiating objects, I am not against it, but it will not be the default behaviour.

Also, please, update readme in the pull request.

o-fedorov commented 5 years ago

Good. Thank you. Updated the README, hope the text is Ok

o-fedorov commented 5 years ago

Thank you for accepting the PR. Cold you please notify me when the new version is released? I would like to use the change in my current projects

ivankorobkov commented 5 years ago

Done. Added you to the contributers. https://pypi.org/project/Inject/