Skip to content
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

Overload all operators #151

Open
cgarciae opened this issue Apr 28, 2020 · 1 comment
Open

Overload all operators #151

cgarciae opened this issue Apr 28, 2020 · 1 comment

Comments

@cgarciae
Copy link

Hey, awesome library! I am new to nim and was trying out some basic python integration with nimpy, I am impressed :D

I was wondering if we could try to overload all operators for PyObject so basic stuff like addition and subtraction work out of the box. Currently I managed to do it like this:

import nimpy

let operator = pyImport("operator")
let np = pyImport("numpy")

proc `+`(a: PyObject, b: float): PyObject = operator.add(a, b)
proc `+`(a: PyObject, b: int): PyObject = operator.add(a, b)

echo(np.array([1,2,3]) + 20.0)
echo(np.array([1,2,3]) + 5)

We would have to do all combinations of operators + types + swapping a and b, maybe this could be automated via e.g. a jinja2 template. They also did this in the PythonKit library for Swift here.

@DylanModesitt
Copy link

DylanModesitt commented May 25, 2020

You can get some of the way there with just making the operator generic in A and B

proc `+`[A, B](a: A, b: B): PyObject =
    callObject(getAttr(operator, "add"), a, b)


proc `*`[A, B](a: A, b: B): PyObject =
    callObject(getAttr(operator, "mul"), a, b)


echo(np.array([1,2,3]) + 20.0)
echo(20.0 + np.array([1,2,3]))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants