codon icon indicating copy to clipboard operation
codon copied to clipboard

Unable to pass a function as an argument

Open km19809 opened this issue 2 years ago • 2 comments

Description

I am not able to pass a function as an argument, to python functions. I found the issue by calling matplotlib.animation.FuncAnimation. However, the full code was too long, so I made a minimum example to reproduce.

How to reproduce In codon v0.15.5:

def add(a,b):
    return a+b

@python
def debug(f):
    print(f, type(f))

@python
def debug_call(f, args):
    f(*args)

debug(add)
debug_call(add, (1, 3))

Result:

((), ()) <class 'tuple'>
PyError: 'tuple' object is not callable

Raised from: pyobj.exc_check:0
/home/minsoo/hobby/codon-deploy/lib/codon/stdlib/internal/python.codon:623:13

Backtrace:
  [0x7f6a618a6c94] GCC_except_table193 at /home/minsoo/hobby/codon-deploy/lib/codon/stdlib/internal/python.codon:623:13
  [0x7f6a618a6cc0] GCC_except_table193 at /home/minsoo/hobby/codon-deploy/lib/codon/stdlib/internal/python.codon:626:9
  [0x7f6a618a7cba] GCC_except_table193 at /home/minsoo/hobby/codon-deploy/lib/codon/stdlib/internal/python.codon:650:68
  [0x7f6a618a7d44] GCC_except_table193 at /home/minsoo/hobby/codon-playground/high_order.py:9:1
  [0x7f6a618ae1c2] GCC_except_table193 at /home/minsoo/hobby/codon-playground/high_order.py:13:21
[1]    1244 abort      ../codon-deploy/bin/codon run high_order.py

km19809 avatar Mar 18 '23 06:03 km19809

Thanks for the report, @km19809 -- this is something I think we can support, although it's not trivial as we essentially need to generate a Python function object to wrap a native Codon function, which on the surface shouldn't be too difficult but can become complicated when considering e.g. default args, variable/keyword-args, captured variables, etc. The actual error you see is because Codon passes functions around as tuples that contain other info like default args or captures. We'll investigate this more for a future release!

arshajii avatar Mar 20 '23 14:03 arshajii

Thanks. I know the difficulty of sending typed functions (especially generic functions) to Python. However, we cannot pass even @python functions for now.

@python 
def add(a,b):
    return a+b

The above example produces the same result.

As you know, it is common to use high-order functions in Python. So, I'll accept any restrictions on the function definition as long as I can pass it to Python. I hope codon can achieve this without introducing much complexity.

km19809 avatar Mar 20 '23 15:03 km19809