Python2项目升级python3,自动格式化技巧
原创: PythonicPython PythonicPython 2018-12-20
1,2to3.py => python3官方自带的代码升级脚本
几乎所有的Python 2程序都需要一些修改才能正常地运行在Python 3的环境下。为了简化这个转换过程,Python 3自带了一个叫做2to3的实用脚本(Utility Script),这个脚本会将你的Python 2程序源文件作为输入,然后自动将其转换到Python 3的形式。
python 2to3.py -w <proiect_dir>
命令行执行这条语句,把 project_dir 换成想要更改的文件夹地址,脚本会执行并把python2代码格式化为python3,并生成同名文件 xxx.py.bak用来回滚。这个脚本可以解决大量的语法兼容问题。
2,string问题
首先这个就是Python语言本身的问题,因为在Python2的语法中,默认的str并不是真正意义上我们理解的字符串,而是一个byte数组,或者可以理解成一个纯ascii码字符组成的字符串,与python3中的bytes类型的变量对应,而真正意义上通用的字符串则是unicode类型的变量,它与Python3中的str变量对应本来应该用作byte数组的类型却用来做字符串,之所以这样做是为了与之前的程序保持兼容。
下面是其对应关系:
py2 py3
str <===> bytes
unicode <===> str
3,python3主要带来了哪些更新
* print 由statement 变为function
print ‘hello world’ ==> print('hello world')
* str is unicode, (not bytes)
* super() 的更新
py2: >>> class ParentCls(object): ... def foo(self): ... print "call parent" ...>>> class ChildCls(ParentCls): ... def foo(self): ... super(ChildCls, self).foo() ... print "call child"... >>> p = ParentCls() >>> c = ChildCls() >>> p.foo() call parent >>> c.foo() call parentcall child
py3 >>> class ParentCls(object): ... def foo(self): ... print("call parent") ...>>> class ChildCls(ParentCls): ... def foo(self): ... super().foo() ... print("call child") ...>>> p = ParentCls() >>> c = ChildCls() >>> p.foo() call parent >>> c.foo() call parentcall child
* 函数的参数类型提示
>>> import types >>> generator = types.GeneratorType >>> def fib(n: int) -> generator: ... a, b = 0, 1 ... for _ in range(n): ... yield a ... b, a = a + b, b ...>>> [f for f in fib(10)] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
* 新的变量声明方式
>>> from typing import List, Dict >>> class Cls(object): ... x: List[int] = [1, 2, 3] ... y: Dict[str, str] = {"foo": "bar"} ...>>> o = Cls() >>> o.x[1, 2, 3] >>> o.y{'foo': 'bar'}
* 字符串的新玩法
>>> py = "Python3" >>> f'Awesome {py}' 'Awesome Python3'
* Data Class
>>> from dataclasses import dataclass >>> @dataclass ... class DCls(object): ... x: str ... y: str ...>>> d = DCls("foo", "bar") >>> dDCls(x='foo', y='bar')
* 断点调试 breakpoint()
breakpoint 是一个内建函数,断点十分方便,可以告别PDB了
>>> for x in range(3): ... print(x) ... breakpoint() ...0> <stdin>(1)<module>()->None (Pdb) c 1 > <stdin>(1)<module>()->None (Pdb) c 2
* async相关 (后面单列一篇)
本人公众号: