samedi 29 février 2020

How to implement this lazy loading pattern?

The following code exemplifies the initial situation on which I want to improve:

# expensive function execution returning a value
def f(x:int):
    print(x)
    return 2*x

# the value is to be stored globally
gvar = f(3)

# this function uses the global variable
def g():
    print(gvar)

First of all I don't want gvar to be set immediately but upon the first time it is used (lazy loading):

gvar = None

def g():
    gvar = f(3)
    print(gvar)

But also I don't want gvar to be set every time it is used as well:

gvar = None

def g():
    if gvar is None:
      gvar = f(3)

    print(gvar)

And finally I want this to happen as transparently as possible - the result should be something similar to this:

gvar = magic(f, 3)

def g():
    print(gvar)

So I can just use gvar as if it was a normal variable while it actually invisibly encapsulates a mechanism that will lazy load its value.

Is that possible?


To give you further context. The practical scenario is a FastApi service where g() would represent a path. Several of those endpoints might use the same global variable which should only be used once. To make the pattern more reusable and pluggable I would like the lazy loading to happen transparently.

Aucun commentaire:

Enregistrer un commentaire