In python, call a function in the way of accessing a variable with the help of LocalProxy

Imagine this: everytime you access a variable, a bound function is called and the function's return will be the variable's value. We use LocalProxy to make this magic happen.

Example usage

For example, we have a utility function get_new_id:

_id = 0

def get_new_id():
    global _id
    _id += 1
    return _id

Everytime we need to use a new id, we call get_new_id():

print(get_new_id())
print(get_new_id())
print(get_new_id())
# output:
# 1
# 2
# 3

Calling a function may be annoying, is it possible to get a new id without calling a function? Maybe something like this:

print(new_id)
print(new_id)
print(new_id)
# the output we want:
# 1
# 2
# 3

Solution

First, install Werkzeug:

pip install Werkzeug

Then, use LocalProxy to wrap get_new_id:

from werkzeug.local import LocalProxy

new_id = LocalProxy(get_new_id)

print(new_id)  # this equals to print(get_new_id())
print(new_id)
print(new_id)
# output:
# 1
# 2
# 3

new_id = LocalProxy(get_new_id) means that, every time you access new_id, you get the return of get_new_id().

Old style New style with equivalent effect
print(get_new_id()) print(new_id)
Posted on 2022-05-01