Author Topic: How to set a default function argument  (Read 511 times)

pyuser

  • Newbie
  • *
  • Posts: 8
  • Karma: +0/-0
    • View Profile
How to set a default function argument
« on: April 08, 2015, 08:34:12 PM »
Hi,

Could you please let me know how I can set a default function input parameter with xlfunc?

For example:

@xl_func("float x, int n: float")
def py_round(x, n=2):
    return round(x, n)

But in excel, if I call py_round(x), it doesn't really use the default value n=2.

I also tried with header  -  @xl_func("float x, int n=2: float"), but it doesn't work either.

Any information will be highly appreciated.

Thanks!

Tony

  • Administrator
  • Hero Member
  • *****
  • Posts: 574
  • Karma: +13/-1
    • View Profile
Re: How to set a default function argument
« Reply #1 on: April 09, 2015, 10:12:36 AM »
Hi,

unfortunately default arguments are not supported in Excel functions. This is because of the way Excel handles missing arguments. If you don't specify arguments when calling the function Excel will call the underlying function implementation with its own default values, which depend on the argument type. There is no way when registering a function to say what the default value should be. This is a limitation of the Excel XLL SDK.

If you use the 'var' type a missing value will be passed as None, which you can check for and substitute with your default value. This isn't as convenient as python's keyword argument defaults but it should be workable.

This has come up before. I'll have a think about whether or not there's something that come be done in PyXLL to work around this limitation and somehow make it 'just work' - but for now I'm afraid you're stuck with the above suggestion.

Best regards,
Tony

pyuser

  • Newbie
  • *
  • Posts: 8
  • Karma: +0/-0
    • View Profile
Re: How to set a default function argument
« Reply #2 on: April 09, 2015, 04:09:55 PM »
Thank you for all the info. Tony!