编程语言
首页 > 编程语言> > 哪个2to3修复程序输出有效的Python 2代码?

哪个2to3修复程序输出有效的Python 2代码?

作者:互联网

2to3 is a Python program that reads Python 2.x source code and applies a series of fixers to transform it into valid Python 3.x code

考虑一下https://docs.python.org/3.4/library/2to3.html#fixers列出的四十个修复者.按照设计,它们都输出有效的Python 3代码.哪个输出有效的Python 2代码?

例如,“将旧的不相等语法<>转换为!=”的修复器NE具有此属性,因为!=是有效的Python 2以及Python 3.

而“将__nonzero__重命名为__bool__”的修复程序NONZERO没有该属性,因为Python 2.7中没有函数__bool__.

解决方法:

What’s New In Python 3.0开始:

It is not recommended to try to write source code that runs unchanged
under both Python 2.6 and 3.0; you’d have to use a very contorted
coding style, e.g. avoiding print statements, metaclasses, and much
more. If you are maintaining a library that needs to support both
Python 2.6 and Python 3.0, the best approach is to modify step 3 above
by editing the 2.6 version of the source code and running the 2to3
translator again, rather than editing the 3.0 version of the source
code.

那个链接非常好,因为它还列出了3.0中的大多数主要新功能和更改

至于你的问题,我能找到的最接近你要求的是Six,它不是转换器或修复器,而是一个兼容性库,可以为你处理大量的扭曲编码.也就是说,我不知道它的工作情况如何,并且无论如何都需要对现有代码进行大量更改才能充分利用它.

主要问题是Python 3.x改变了语法的许多基本方面,因此在没有某种兼容层的情况下,相同的代码几乎不可能在3.x和2.x上以相同的方式工作. Python 2的字符串与Python 3的字符串不同.对于整数来说也是如此,Python 3甚至不再具有long类型(Python 3 int就像以前那样长,而旧的Python 2 int已经不见了).许多内置函数和属性已被重命名或修改,并且大多数语法已经以完全破坏向后兼容性的方式进行了更改或清理.

Porting code to Python 3 with 2to3解释了一下大约2to3及其作用,并且列出的大量语法更改应该足以解释为什么结果代码不再适用于Python 2.x.

标签:python,python-3-x,python-2to3
来源: https://codeday.me/bug/20190708/1403323.html