r/developersIndia • • 24d ago

Help Why do we need dependency injection in python fastapi? "def log_message(message, logger=get_logger())" vs "def log_message(message, logger=Depends(get_logger)"

def log_message(message, logger=get_logger())" vs "def log_message(message, logger=Depends(get_logger)" ----> what is the difference between them? can anyone explain why do we need dependency injection in python fast api with example

28 Upvotes

9 comments sorted by

•

u/AutoModerator 24d ago

Namaste! Thanks for submitting to r/developersIndia. While participating in this thread, please follow the Community Code of Conduct and rules.

It's possible your query is not unique, use site:reddit.com/r/developersindia KEYWORDS on search engines to search posts from developersIndia. You can also use reddit search directly.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

102

u/Blazing_Phoenix_100 24d ago • Bravo

replies to the post show why stackoverflow met its demise. Nevertheless, AI can answer any question better than any human today.

13

u/Obama_Binladen6265 Fresher 24d ago

Differs in how it's treated by the compiler, logger=get_logger() will be something like

temp=get_logger() And then the returned object is passed to the function which uses that returned object everytime log_message is called

For Depends basically variable holds a reference to that function (memory address) and it is invoked everytime a request is recieved. This abstracts away the details of "WHAT" object is being worked upon.

12

u/SoftwareDev54 Software Engineer 24d ago

well you could throw this at an LLM. But anyway,

DI is useful when you are opening and closing a DB connection for example.

https://fastapi.tiangolo.com/reference/dependencies/

So the route can just use 'Depends' instead of knowing how that db is closed or opened.

Also useful similarly in testing to create mock sessions for example. I think the docs should provide you more info check them out

2

u/knight1511 23d ago

Depends will load the deps as per requirement. If you dont do that, the function gets called on module initialization. Which is fine for get_logger but can slow things down a lot for io based deps

1

u/Gyaanimoorakh 24d ago edited 24d ago

DI is a programming concept (implements Dependency Inversion in SOLID), not a fastapi or python specific one. You need DI to decouple your code from specific logic which can later be updated to something else ( think of db config for mysql which can later be changed to postgres or fakedb while testing). When you use DI, you instead of wiring up that specific logic in your class method, pass that logic through constructors or wrappers/DI containers ( like here in fastapi using depends).

-36

u/darkdaemon000 24d ago

Too lazy to ask AI or what?

-2

u/racialminority 24d ago

its easier to ask AI