pyppin.base.lazyinit

[View Source]

An instance method decorator to make initializers execute once, on demand.

Functions

lazyinit(method)

An instance method decorator to make it lazy-init and execute once.

reset_all(holder)

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.

pyppin.base.lazyinit.reset_all(holder: object) None[source]

Reset all lazyinit’ed variables inside a particular object.

This is almost exclusively useful in unittests, if you need to hard-reset some kind of environment variable or something.