
1
新的特性
1).import异常
2).__file__路径
import sys
print(__file__)
print(sys.argv[0])
print(sys.path[0])
得到结果如下:
3).replace修复
replace是字符串处理中的常用函数,他的原型其实是这样的:
str.replace(old, new[, max])
s = ''
s = s.replace('', 'python39', 1)
print(s)

2
模块改动
Python3.9并没有为我们带来新的内置模块,但是对一些模块进行了修改,我们挑选几个使用相对较多的进行说明。
1).ast
import ast
func_def = 'print(3+5)'
r_node = ast.parse(func_def)
print(ast.dump(r_node))
先使用之前的版本来运行,看看下图中的输出结果。我们不用看内容,单从输出格式而言,这串代码既没有换行也没有缩进,看起来很费劲。
import ast
func_def = 'print(3+5)'
r_node = ast.parse(func_def)
print(ast.dump(r_node, indent=2))
然后用python3.9来运行,结果如下,这次看起来是不是舒服多了。
2).asyncio
3).threading
4).pprint
import pprint
from types import SimpleNamespace
K = [str(i) for i in range(10)]
L = [str(i)*20 for i in range(10)]
D = dict(zip(K, L))
sn = SimpleNamespace(**D)
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(sn)
再来看python3.9中使用pprint的输出结果(下图),这下知道区别在哪了吧。

3
其他优化
1).Build和C API
-
提供Py_EnterRecursiveCall()和Py_LeaveRecursiveCall()作为limited API的常规函数。 从stable API中删除_Py_CheckRecursionLimit。 -
向C API添加一个新的公共函数PyObject_CallNoArgs(),这个函数可以调用不含参数的可调用Python对象。 -
全局变量PyStructSequence_UnnamedField在python3.9中修改为常量字符串。 -
从Py_LIMITED_API.pyfpe.h中剔除PyFPE_START_PROTECT()和PyFPE_END_PROTECT()函数。 -
删除PyMethod_ClearFreeList()和PyCFunction_ClearFreeList()函数。
2).方法调整
-
在之前的版本中,math.factorial()函数只接受非负整数值,否则将引发ValueError。 在python3.9中该函数将弃用,任何参数都将引发TypeError。 -
弃用parser模块,并将在以后的Python版本中删除。 -
修改random模块的seeds类型,今后只支持None,int,float,str,bytes和bytearray类型。 -
始终允许打开GzipFile文件进行读写,即使不指定mode参数也不会发出警告。 -
推荐使用_tkinter.TkappType的splitlist()方法代替split()方法。
3).移除模块
-
collection.abc 里面的抽象基类将不在常规的 collection 模块中公开。 -
删除 sys.getcheckinterval() 和 sys.setcheckinterval() 函数。 -
删除threading.Thread 的 isAlive() 方法。 -
删除 ElementTree 中的getchildren() 和 getiterator()方法。 -
删除 旧 plistlib 模块的实现,同时删除其中的use_builtin_types 参数。
更多有趣有用文章

老司机吐槽
