wlav / cppyy

Other
400 stars 41 forks source link

Convert None to Default Parameter #69

Closed mkolin closed 2 years ago

mkolin commented 2 years ago

This library has been pretty amazing. A nice enhancement would be to convert a python None to a default parameter in C++:

import cppyy
cppyy.cppdef('''
... void FuncWithOptionalParam(int x, int y = 0) {}
... ''')

from cppyy.gbl import FuncWithOptionalParam
FuncWithOptionalParam(1)
FuncWithOptionalParam(1, 2)
FuncWithOptionalParam(1, None)
TypeError: void ::FuncWithOptionalParam(int x, int y = 0) =>
    TypeError: could not convert argument 2 (int conversion expects an integer object)

Not important at all, but it would be great if the last call would instantiate FuncWithOptionalParam(1, 0).

wlav commented 2 years ago

What is the motivating use case? None plays a lot of roles in Python and giving it all the same roles in C++ has been a source of trouble (e.g. overload resolution and use of return types), so over time, I've been restricting it further and further to eventually only mean void.

mkolin commented 2 years ago

Oftentimes, we have a python wrapper function that has a similar signature. It would be nice to just pass the params in as is.

def func_with_optional_param(x, y=None):
  FuncWithOptionalParam(x, y)

Right now there has to be some sort of check for None. It's not really necessary, just a nice to have. I understand not wanting to use None in more cases, though.

wlav commented 2 years ago

Where is None coming from? Is it written like in the code snippet above? If yes, then a simpler solution, one with no possibility for confusion, is to create a new magic variable called cppyy.default which then is interpreted as "result of the default constructor" which for an int argument means int() i.e. 0 of type int.

mkolin commented 2 years ago

Thanks! We can give that a try.

wlav commented 2 years ago

It doesn't exist yet. :) If this is a workable idea, it's trivial to implement, though.