I'm writing a program that needs to be compatible for both Python 2.X and Python 3.X. My problem is that, because of the differences between these two versions, I'm duplicating code.
try:
### Python 2.X part
time.sleep(iterator.next())
if len(arguments) >= len(inspect.getargspec(task).args):
task(*arguments)
else:
print("ERROR: There is a mismatch between the number of"
" arguments provided in `arguments` and the ones"
" needed by the task function.")
except AttributeError:
### Python 3.X part
time.sleep(next(iterator))
if len(arguments) >= len(inspect.getfullargspec(task).args):
task(*arguments)
else:
print("ERROR: There is a mismatch between the number of"
" arguments provided in `arguments` and the ones"
" needed by the task function.")
It can be seen that both versions only differ in the usage of next()
, inspect.getargspec()
and inspect.getfullargspec()
, while the other logic remains the same. Is there any way to optimize the execution of the tasks, in tasks(*arguments)
, and the printing of the error messages, so that I don't have to repeat the same code? This is just sample working code, but I mean my question in a more broader and general case.