pythonlazy-initializationproxy-classes

Proxy object for lazy initialization


Are there any ready-to-use Python module that provides an easy to use proxy object that only initializes the "real" object when really needed?

Ideally I'm looking for a transparent implementation so that code dealing with this proxy object does not need to be aware that it is not the actual object.

I want to use it like this:

class Example:
    def __init__(self):
        print("Example initialized")

lazy = Proxy(Example)
print(isinstance(lazy, Example))
# Example initialized
# True

As you can see it would behave very much like a unittest.MagicMock.

If there aren't any libs offering functionality like this out there I'll implement it myself but I want to be sure no one else have done this yet.

EDIT

I expect this proxy object to follow a through implementation like this.


Solution

  • I've found module lazy-object-proxy which does exactly that.

    Worth mentioning that as @Marat pointed out Django offers a solution as well, though I do not want to import Django just for that, if you're already using it in your project it will be a perfectly fine solution.