-
Notifications
You must be signed in to change notification settings - Fork 170
Figure out how to handle generic functions #141
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
So one good design might be: from ltypes import generic_function
@generic_function("sin")
def sin_f32(x: f32) -> f32:
...
@generic_function("sin")
def sin_f64(x: f64) -> f64:
... And we implement the |
Python has from ltypes import overload
@overload
def sin(x: f32) -> f32:
...
@overload
def sin(x: f64) -> f64:
... The CPython implementation of the |
Here is the example of python's overload: from typing import overload
@overload
def foo(x: int) -> int: ...
@overload
def foo(x: str) -> str: ...
def foo(x: str | int) -> str | int:
return x
print(type(foo(2)), type(foo('2'))) Output: For this we need to add the ellipsis (#146) both in AST and ASR. |
I tried implementing the Python Script
from inspect import getfullargspec, getcallargs
global_map = {}
class Dummy:
def __init__(self, name):
self.func_name = name
def __call__(self, *args, **kwargs):
func_map_list = global_map.get(self.func_name, False)
if not func_map_list:
raise Exception("Function not defined")
for item in func_map_list:
func, key = item
try:
ann_dict = getcallargs(func, *args, **kwargs)
except:
continue
f = True
for k, v in ann_dict.items():
if not key.annotations.get(k, False):
f = False
break
else:
if type(v) != key.annotations.get(k):
f = False
break
if f:
return func(*args, **kwargs)
raise Exception("Function not found with matching signature")
def overload(f):
dummy = Dummy(f.__name__)
f_list = global_map.get(f.__name__, [])
f_list.append((f, getfullargspec(f)))
global_map[f.__name__] = f_list
return dummy
@overload
def foo(a:int, b:int):
return a*b
@overload
def foo(a:int):
return a**2
print(foo(2), foo(2, 10)) It seems to be working fine, though it might require a bit of more testing. |
Perfect! Please submit it as a PR, put |
Couple comments to the implementation:
Otherwise this looks great. |
I'm now thinking to extend the overload support to LPython. |
So that you can implement a function
sin(x)
in LPython, that would work both forf32
andf64
.The tricky part is to design this in such a way so that it works with CPython also.
The text was updated successfully, but these errors were encountered: