Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 733
Rodrigo Martins de Oliveira Avatar asked Jan 17 '26 10:01

Rodrigo Martins de Oliveira


1 Answers

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.

like image 138
Rodrigo Martins de Oliveira Avatar answered Jan 20 '26 02:01

Rodrigo Martins de Oliveira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!