Python2项目升级python3,自动格式化技巧

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相关 (后面单列一篇)

 

本人公众号:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值