pyppin.base.lazyinit¶
An instance method decorator to make initializers execute once, on demand.
Functions
|
An instance method decorator to make it lazy-init and execute once. |
|
Reset all lazyinit'ed variables inside a particular object. |
- pyppin.base.lazyinit.lazyinit(method: Callable[[Any], T]) _LazyInitializedProperty[T] [source]¶
An instance method decorator to make it lazy-init and execute once.
The resulting variable behaves like a property, where the function is only invoked once and the result memoized.
Why would you do this? It makes it really easy to write complicated initializers!:
class MyClass(object): @lazyinit def fooService(self) -> FooService: ... do something complicated to create a FooService @lazyinit def barService(self) -> BarService: # Note how you can use one lazy-init in another. Don't create infinite loops, # for obvious reasons. return BarService(self.fooService, "bar")
If you actually need to change the value of the field – this is very rare and mostly happens in unittests – you can explicitly set it (
quux.fooService = FooService(...)
), or delete the attribute (del quux.fooService
) in order to force it to reinitialize the next time it’s called.