0

I have some python3 code that I'm trying to make compatible with python2. This has mostly been easy using the six package and __future__, but I can't find a way around 'extended unpacking' (i.e. using the *args syntax). For example, the function:

def func(a, *args, b=None, **kwargs):
    pass

What is the most elegant and/or simplest way to make this compatible with both python2 and python3? Is there any solution in six, e.g. a wrapper or something?

While the question "Default arguments with *args and **kwargs" is similar, it's solution is to use a different function instead of making the example one work (although, of course, that may be impossible). i.e. func(a, b=None, *args, **kwargs) instead.

Since it raises a SyntaxError before execution a try-except won't work...

DilithiumMatrix
  • 17,795
  • 22
  • 77
  • 119
  • 1
    Basically impossible with this syntax, as Python 2 AST does not support this. Closest way this can be done also in Python 2 is to manually pop `b` from `kwargs`. – metatoaster Aug 15 '18 at 01:46
  • @metatoaster if "basically impossible" means "impossible", then that seems like a complete answer – DilithiumMatrix Aug 15 '18 at 01:54
  • Which is what one of the answers in that linked question said. – metatoaster Aug 15 '18 at 01:55
  • Really though, it isn't _completely_ impossible, if dynamically modifying the input source file to generate a Python 2 compatible AST that satisfies the constraints are done (see: [this answer](https://stackoverflow.com/a/39413170/2904896) for an idea how this might be done; but instead of writing back out the file, it would be compiled and added to `sys.modules`). – metatoaster Aug 15 '18 at 01:58

0 Answers0