How can I hide incompatible code from older versions of Python?

I am writing unit tests for a function that takes both an argument *argsand a **kwargs. A reasonable use case for this function is to use the keyword arguments after the segment *args, i.e. the form

def f(a, *b, **c):
    print a, b, c

f(1, *(2, 3, 4), keyword=13)

Now it has only become legal in Python 2.6 ; in earlier versions, the above line is a syntax error and therefore does not even compile into bytecode.

My question is: . How can I test the functionality provided in the new version of Python and still run tests for older versions of Python?

I must point out that the function itself works fine for earlier versions of Python, only some calls are syntax errors before Python 2.6. The various methods that I saw for checking the version of Python do not work for this, since it does not go through the compilation stage.

I would prefer not to split the tests into multiple files, if at all possible.

+3
source share
3 answers

I don't think you should test if Python is working properly; instead, focus on testing your own code. At the same time, it is quite possible to write a specific call in a way that works for all versions of Python, namely:

f(1, *(2,3,4), **{'keyword':13})
+11
source

eval() exec Python. , , .

+2

Why do you want to use this syntax? I mean that this function 2.6 does not bring any real benefits, except for the shortcut.

a = [2,3,4]
a.insert(0, 1)
kw = {'keyword'='test'}
f(*a, **kw)
+1
source

Source: https://habr.com/ru/post/1715797/


All Articles