0

In my application I need to create functions parameterized by a dictionary, and I use functools.partial for it, see this simplified example:

import functools

def check_bounds_general(key, value, bounds):
    return bounds[key][0] < value < bounds[key][1]

bounds = {"a":(0, 3), "b":(1,4)}

check_bounds_specific = functools.partial(check_bounds_general, bounds=bounds)

assert check_bounds_specific("a", .1)
assert not check_bounds_specific("a", 3.4)
assert not check_bounds_specific("b", 1)
assert check_bounds_specific("b", 3.4)

My issue is that I need to compile this check_bounds_specific function with numba and numba doesn't like closures/partial functions. So is there a way to tell Python to turn this partial function into a normal function making a copy of the namespace and injecting it somehow into the function?

My objective is to create a function like:

def check_bounds_specific(key, value):
    bounds = {"a":(0, 3), "b":(1,4)}
    return bounds[key][0] < value < bounds[key][1]

But dynamically. Then this function is easy to optimize with numba.

Andrea Zonca
  • 8,378
  • 9
  • 42
  • 70
  • What is not working with closures? eg. an example that uses closures: https://stackoverflow.com/a/58752553/4045774 – max9111 Oct 24 '22 at 12:35
  • @max9111 it is passing variables into the closure, see https://stackoverflow.com/questions/74160505/numba-and-variables-in-the-namespace-of-a-factory-function?noredirect=1#comment130939719_74160505 – Andrea Zonca Oct 24 '22 at 20:14
  • Maybe I don't get the point. But passing variables in a closure looks to be straight forward. https://pastebin.com/EzBsQifg I am not sure about `cache=True` works to avoid recompilation on every call, between closing the interpreter... If the real problem is a lot more complicated, please include it in your question. Using a dynmaic dict for a simple if else doesn't look efficient.... – max9111 Oct 24 '22 at 20:44

0 Answers0