2

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.

Rodrigo Oliveira
  • 1,452
  • 4
  • 19
  • 36
  • 1
    [`django.utils.functional.lazy`](https://docs.djangoproject.com/en/2.0/_modules/django/utils/functional/) – Marat Feb 06 '18 at 01:37
  • @Marat This seems to suit my needs. Though there are two downsides: to use it I would need to import the whole DJango module; and their docs does not expose this piece as stable: _Most of the modules in django.utils are designed for internal use [...]_. While they specify some parts of django.utils as stable for external use, these lazy objects aren't there. But this is a great start regardless, thanks for pointing it out. – Rodrigo Oliveira Feb 06 '18 at 02:19

1 Answers1

3

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.

Rodrigo Oliveira
  • 1,452
  • 4
  • 19
  • 36