-1

Is there a way to keep the Python 3 syntax for calling a default parameter after *args while still being Python 2-compatible?

I have a function like so:

def foo(*args, bar='test'):
    pass  # do stuff with args and bar

The problem is the module needs to be compatible with both Python 2 and 3, therefore the default argument after *args won't work. I've seen this answer, which recommends doing

def foo(*args, **kwargs):
    bar = kwargs.pop('bar', 'test')
    # do stuff with args and bar

Which works, but is undeniably less clear than the first method. The nice thing about the first method is it is partially self-documenting, whereas with the second one the user has to search around a bit to figure out what's going on. And Readibility counts.

So, is there a way I can at least have the first method in the module while still having the code run on Python 2.7? For example, possibly writing the function definition twice, once for Py2 and once for Py3?

jpyams
  • 4,030
  • 9
  • 41
  • 66
  • You certainly _can_ write the function twice, but if the second version works for both Python 2 and Python 3, why would you? If your goal is clarity, you would be making your function more unclear by having two versions of it. Just putting a comment on your function would be clearer and easier. – khelwood Nov 24 '17 at 15:55

1 Answers1

0

No you cannot have a function using the Python 3 form in a file used by the Python 2 interpreter. That's because the keyword-only argument placed after the *args is a change to the Python syntax so it will cause a syntax error in Python 2 before you even get near executing the code.

You will have to either use the Python 2 version in both cases, or use separate source files and only import the correct one.

Duncan
  • 92,073
  • 11
  • 122
  • 156