Finistere / antidote

Dependency injection for Python
MIT License
90 stars 9 forks source link

Inject not wiring #29

Closed vimtor closed 3 years ago

vimtor commented 3 years ago

The following code, partially extracted from the docs:

from antidote import implementation, Service, inject

class Database:
    pass

class PostgresDB(Service, Database):
    def __repr__(self):
        return 'Postgres'

class MySQLDB(Service, Database):
    def __repr__(self):
        return 'MySQL'

@implementation(Database, permanent=True)
def choose_db():
    return PostgresDB

@inject
def print_db(db: Database):
    print(db)

print_db()

Throws the following error:

image

Finistere commented 3 years ago

Hello ! It's not a bug, it's a feature. :D

Had it worked, you would have no way of knowing where the Database is coming from when using print_db(). So Antidote forces you to specify from where the dependency is actually coming from. Example:

@inject([Database @ choose_db])
def print_db(db: Database):
    print(db)

Or with type hint annotations:

from antidote import From
from typing import Annotated

@inject
def print_db(db: Annotated[Database, From(choose_db)]):
    print(db)

If you use it often, you could also use a type alias:

MyDatabase = Annotated[Database, From(choose_db)]

@inject
def print_db(db: MyDatabase):
    print(db)

Hope that helps ! If not, happy to provide more help.

Could you please tell me how you came up with your example ? I'd love to know which parts of the documentation / readme need to be improved or are missing. Or if you simply didn't read a section because it was too long, simple or complex. :)

Finistere commented 3 years ago

Oh I see now the issue with the documentation. Indeed the "How to / Use interface" is wrong. I'm surprised it passes the doctests, I probably mixed things.

Finistere commented 3 years ago

Fixed, the stable documentation seems to have stopped updating at v0.10 for an unknown reason. Sorry about that. I also updated the interface recipe in the documentation to be more informative.

Let me know if this wasn't the source of your issue !

Finistere commented 3 years ago

Closing, the issue is fixed.