This example is contrived but represents a real life situation:
I have a python script that takes command line arguments.
main()
will parse the arguments, and pass them on to an intermediate function (caller_func
in the code example)The intermediate function will then call a decorated function (
fib()
in the example) that is decorated withlru_cache
fromfunctools
, and themaxsize
of the cache is an argument to be accepted from command line and passed via the intermediate function.
How do I do this?
import argparse
from functools import lru_cache
def main():
# boilerplate for parsing command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("--cache_size", default="10")
parser.add_argument("--fibo_num", default="20")
args = parser.parse_args()
cache_size = int(args.cache_size)
fibo_num = int(args.fibo_num)
caller_func(cache_size, fibo_num)
#Intermediate function that is supposed to call decorated function
def caller_func(cache_size, fib_num):
print(fib(fib_num))
#function decorated by LRU cache
@lru_cache(maxsize=cache_size)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
if __name__ == "__main__":
main()
run as
python3 example.py --cache_size 5 --fibo_num 30
throws
NameError: name 'cache_size' is not defined
I tried making cache_size
a global variable, but it didn't work, and I don't want globals anyway.