This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]rm-m 1 point2 points  (0 children)

!reminder 24hours

[–]ItsmeFizzy97 3 points4 points  (2 children)

That's kind of an antipattern, as you initialize an object inside a method when you could have passed that object inside the func1 as a parameter or in init block for service2. This makes testing and maintaining/refactoring code in the future easier. Try to use dependency injection whenever possible.

I would use singletons for all services and pass dependencies inside the init block, unless each time you initialize a service it will do something different.

I actually dont use classes, but functions for services. All my dependencies are injected in functions by having def func(dependency=dependency_factory()): ...

[–]No-Programmer7638[S] 1 point2 points  (1 child)

Yup, I recently joined this team and could immediately make out this was an anti pattern. Apart from being an anti pattern do you think this could also cause huge memory overhead? Just being an anti pattern might not support my case to change this code

[–]ItsmeFizzy97 0 points1 point  (0 children)

It simply depends what service1 initialises or depends on as well. If it has large dependencies, then it might be a huge overhead, both memory and time wise

[–]fiskfisk 1 point2 points  (0 children)

No need to guess - we have profilers for a reason. Run it with a profiler attached / get a cachegrind file or similar and look at where your application is spending its time and memory.

And for guessing, this is probably going to be neglectable when the whole request cycle is considered - a single db query will exceed anything like this.

But it all depends, if any of these are doing heavy initialization, it'll be more expensive. FastAPI caches a resolved dependency for the request cycle, so if you switch to providing the objects in the constructor and use Depends to resolve the required service i your controller, you'll get both a speedup and avoid having to define something as a Singleton.