[Fixed] Using functools.partial in modules

I’m trying to use functools.partial in a module
unfortunatly functools is not yet implemented in Skulpt

Attempting to recreate this functionality myself I created the function

def merge_two_dicts(x, y):
  x.update(y)
  return x


def partial(fun, *part_args, **part_kwargs):
  def wrapper(*extra_args, **extra_kwargs):
    args = list(part_args)
    args.extend(extra_args)
    kwargs = merge_two_dicts(part_kwargs, extra_kwargs)
    return fun(*args, **kwargs)
  return wrapper

Testing

test_fun = lambda x, y: x + y*2
fun = partial(fun, 1)
print(fun(2))

This code works fine in python3 on my local machine (giving 5).
In an anvil module this gives the error

UnboundLocalError: local variable ‘x’ referenced before assignment
at anvil-app-modules/Form1.py, line undefined

What is the best way to achieve this functionality

Yep, that’s a bug in Skulpt. Looks like closures don’t currently work with vararg arguments. We’ll get on that, but as a workaround, here’s a modified implementation of partial that works - if you make explicit variables to carry these values, the closure works:

def partial(fun, *part_args, **part_kwargs):
  pk = part_kwargs
  pa = part_args
  def wrapper(*extra_args, **extra_kwargs):
    args = list(pa)
    args.extend(extra_args)
    kwargs = merge_two_dicts(pk, extra_kwargs)
    return fun(*args, **kwargs)
  return wrapper

(Moved to Bug Reports forum)

Great,
Thanks for the quick reply

functools is now available in skulpt