简体   繁体   English

如何从旧的Python版本中隐藏不兼容的代码?

[英]How can I hide incompatible code from older Python versions?

I'm writing unit tests for a function that takes both an *args and a **kwargs argument. 我正在为一个带有*args**kwargs参数的函数编写单元测试。 A reasonable use-case for this function is using keyword arguments after the *args argment, ie of the form 此函数的合理用例是在*args段之后使用关键字参数,即表单

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

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

Now this only became legal in Python 2.6 ; 现在这只在Python 2.6中变得合法 ; in earlier versions the above line is a syntax error and so won't even compile to byte-code. 在早期版本中,上面的行是语法错误,因此甚至不会编译为字节码。

My question is: How can I test the functionality provided in the newer Python version and still have the tests run for older Python versions? 我的问题是: 我如何测试较新的Python版本中提供的功能,并且仍然可以为较旧的Python版本运行测试?

I should point out that the function itself works fine for earlier Python versions, it is only some invocations that are syntax errors before Python 2.6. 我应该指出,函数本身适用于早期的Python版本,只有一些调用是Python 2.6之前的语法错误。 The various methods I've seen for checking the Python version don't work for this as it doesn't get past the compilation stage. 我看过检查Python版本的各种方法不适用于此,因为它没有超过编译阶段。

I would prefer not to have to split the tests into multiple files if at all possible. 如果可能的话,我宁愿不必将测试分成多个文件。

I don't think you should be testing whether Python works correctly; 我认为你不应该测试Python是否正常工作; instead, focus on testing your own code. 相反,专注于测试自己的代码。 In doing so, it is perfectly possible to write the specific invocation in a way that works for all Python versions, namely: 在这样做时,完全可以以适用于所有Python版本的方式编写特定的调用,即:

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

One approach might be to use eval() or exec along with a test for the current version of Python. 一种方法可能是使用eval()exec以及当前版本的Python测试。 This will defer compilation to runtime, where you can control whether compilation actually happens or not. 这会将编译推迟到运行时,您可以在其中控制编译是否实际发生。

Why do you want to use such syntax? 为什么要使用这样的语法? I mean, this 2.6 feature does not bring any real advantage other than shortcut. 我的意思是,这个2.6功能除了快捷方式之外没有带来任何真正的优势。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM