Skip to content Skip to sidebar Skip to footer

Creating A Decorator / Cache For Checking Global Variable

I've quite a few functions that uses some global variables to hold an object to be reused throughout the library, e.g.: from some.other.lib import Object1, Object2, Object3, Object

Solution 1:

I guess you just want to cache some values. For this the straight forward approach in decent Python without abusing any hidden feature is this:

cache = {}

deffunction1(input):
    try:
        object1 = cache['object1']
    except KeyError:
        object1 = cache['object1'] = Object1
    return object1.func1(input)

And similar for the other functions.

You can also avoid using the still-global variable cache by storing everything within your function object:

deffunction1(input):
    try:
        object1 = function1.object1
    except AttributeError:
        object1 = function1.object1 = Object1
    return object1.func1(input)

This is possible because functions are arbitrary objects to which you can add attributes. But some might call this an abuse and unclean code. As always in such cases, discuss this with your team first and maybe add it to the list of used techniques for this team or project before using it.

I prefer using the hidden feature of mutable arguments:

deffunction(input, object1Cache=[None]):
    if object1Cache[0] isNone:
        object1Cache[0] = Object1
    return object1Cache[0].func1(input)

This works in Python because a list as a default value for a function parameter is still mutable and will keep its value.

And again, this might be considered unclean and an abuse, so discuss this with your team before using it and document in your project notes that this technique is used.

Post a Comment for "Creating A Decorator / Cache For Checking Global Variable"