Python3.8 了解的差不多了吧,Python3.9 新特性了解一下!

640?wx_fmt=png"Python学习开发",一个值得加星标640?wx_fmt=png的公众号。

640?wx_fmt=png

正文共:4946 字 1 图

预计阅读时间:13 分钟

作者:陈祥安

原文有删改:https://docs.python.org/3.9/whatsnew/3.9.html

本文将解释 Python 3.9 中的新特性,而不是 3.8。有关完整的详细信息,请参见更改日志。

目前官网只有 3.8 的下载包,3.9 需要自己编译 Cpython,可以参考我之前的文章里面有编译部分的内容,

语言上的变化

1、使用 Python 进行相对导包的时候,__import__ 出现异常时类型由原来的 ValueError 变成了 ImportError。(由 Ngalim Siregar 在 bpo-37444 中贡献)

"""Resolve a relative module name to an absolute one."""
        bits = package.rsplit('.', level - 1)
        if len(bits) < level:
-          raise ValueError('attempted relative import beyond top-level package')
+            raise ImportError('attempted relative import beyond top-level package')
        base = bits[0]
        return '{}.{}'.format(base, name) if name else base

-:github 中的删除

补充知识:__import__() 函数一般用于动态加载类和函数。

r = __import__('requests_html', globals(), locals(), ['HTMLSession'], 0) 
session = r.HTMLSession()
print(session.get("http://www.baidu.com"))
#globals() 函数会以字典类型返回当前位置的全部全局变量。
#locals() 函数会以字典类型返回当前位置的全部局部变量。

ImportError 触发异常原因:在涉及到相对导入时,package 所对应的文件夹必须正确的被 python 解释器视作 package ,而不是普通文件夹。否则由于不被视作 package,无法利用 package 之间的嵌套关系实现 Python 中包的相对导入。

2、Python 现在获取在命令行上指定的脚本文件名的绝对路径(例如:python script.py:__main__ 模块的 __file__ 属性,sys.argv[0] 和 sys.path[0] 显示的也是绝对路径,而不是相对路径 (这地方之前提出了一个 bug),通过 os.chdir()更改当前目录后,这些路径仍然有效。但是现在出现异常 traceback 信息的时候还会显示

通过命令行执行文件的时候

import sys
print(f"{__file__=}")
print(f"{sys.argv=}")
print(f"{sys.path[0]=}")

运行

$ ./python3 script.py 

结果

__file__='/Users/chenxiangan/cpython/script.py'
sys.argv=['/Users/chenxiangan/cpython/script.py']
sys.path[0]='/Users/chenxiangan/cpython'

但是对于下面这段代码,这段代码请在 Python3.8 下运行

script.js
import sys
import os
modname = 'relpath'
filename = modname + '.py'
sys.path.insert(0, os.curdir)
with open(filename, "w") as fp:
    print("import sys", file=fp)
    print("mod = sys.modules[__name__]", file=fp)
    print("print(f'{__file__=}')", file=fp)
    print("print(f'{mod.__file__=}')", file=fp)
    print("print(f'{mod.__cached__=}')", file=fp)
__import__(modname)
os.unlink(filename)

这个代码意思是动态生产下面的代码

import sys
mod = sys.modules[__name__]
print(f'{__file__=}')
print(f'{mod.__file__=}')
print(f'{mod.__cached__=}')

然后执行完上面的代码,通过 os.unlink 删除。

__file__='./relpath.py'
mod.__file__='./relpath.py'
mod.__cached__='./__pycache__/relpath.cpython-38.pyc'

可以看到还是相对路径,这问题是 Cpython 的 Moudles/getpath.c 的一个 bug 修改内容如下

* absolutize() should help us out below
*/
    else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) &&
-            _Py_isabs(execpath))
+          (wchar_t) execpath[0] == SEP)
    {
        size_t len;
        wchar_t *path = Py_DecodeLocale(execpath, &len);

3、在开发模式和调试模式中,使用 encoding 和 decoding 操作的时候加入 encoding 和 errors 两个关键字参数,errors 是声明在编码或者解码的时候出现错误要如何处理。

str.encode(encoding="utf-8", errors="strict")
bytes.decode(encoding="utf-8", errors="strict")¶

改进的模块

classmethod

类方法现在可以装饰其他描述符了,比如property()。

class C:
    @classmethod
    def f(cls): 
        pass

    @classmethod
    @property
    def age(cls):
       print("haha")

if __name__ == "__main__":
     c=C()
     c.age
     print("over")

输出

haha
over

asyncio

loop.shutdown_default_executor()

调度默认执行程序的关闭,并等待它连接ThreadPoolExecutor中的所有线程。调用此方法后,如果在使用默认执行程序时调用executor()中的loop.run,则会引发RuntimeError。

注意,使用asyncio.run()时不需要调用这个函数。

loop.shutdown_default_executor()

threading

loop.set_default_executor(executor)

将executor设置为executor()中的run使用的默认执行程序。executor应该是ThreadPoolExecutor的一个实例。

all_tasks

从3.7版开始就被弃用了,3.9版中将会删除:不要把它作为任务方法调用。使用asyncio.all_tasks()函数取代。同样的current_task也是用函数asyncio.current_task()取代。

pprint

import types
import pprint
o = types.SimpleNamespace( the=0,
            quick=1,
            brown=2,
            fox=3,
            jumped=4,
            over=5,
            a=6,
            lazy=7,
            dog=8)
pprint.pprint(o)

改版前输出

namespace(a=6, brown=2, dog=8, fox=3, jumped=4, lazy=7, over=5, quick=1, the=0)

改版后输出:

namespace(the=0,
          quick=1,
          brown=2,
          fox=3,
          jumped=4,
          over=5,
          a=6,
          lazy=7,
          dog=8,
          c=3)

importlibimportlib.util.resolve_name() 的异常类型也该为了 ImportError 以前是 ValueError。

不再推荐使用的模块用法

  • parse 模块已被弃用,并将在未来的 Python 版本中删除。对于大多数用例,用户可以使用 ast 模块利用抽象语法树 (AST) 生成和编译阶段。

  • random 模块之前接受任何的 hashable 类型作为种子值,不幸的是,其中一些类型不能保证具有确定性的散列值。Python3.9 中种子值将只接受 None, int, float, str, bytes, and bytearray 类型。

移除的模块用法

  • math.factorial(x)

>>> import math
>>> math.factorial(3)
6
>>> math.factorial(3.0)
<stdin>:1: DeprecationWarning: Using factorial() with floats is deprecated
6
  • collection.abc 里面的抽象基类[https://docs.python.org/3.9/library/collections.abc.html#collections-abstract-base-classes],将不在常规的 collection 模块中公开,这有助于在具体类和抽象基类之间创建更清晰的区别。

  • 删除了从 Python 3.2 开始就弃用的 sys.getcheckinterval() 和 sys.setcheckinterval() 函数。它使用 sys.getswitchinterval() 和 sys.setswitchinterval() 来代替。主要作用分别是返回和设置解释器的 “线程切换时间间隔”。

  • 删除了从 Python 3.8 开始不再推荐使用的 threading.Thread 的 isAlive() 方法,使用 is_alive() 代替。

  • 移除 ElementTree 中在 Python3.2 就已经废弃的方法,getchildren() 和 getiterator(),以 list() 和 iter() 代替。同时删除 xml.etree.cElementTree 方法。

  • 删除 3.4 中不支持的旧 plistlib 模块的实现。使用 load(), loads(), dump(), and dumps() 方法。此外,use_builtin_types 参数已删除,始终使用标准字节对象代替。

  • 修正了当 AssertionError 被隐藏时断言语句的错误行为。加入 LOAD_ASSERTION_ERROR 操作码。

后记

需要注意的是这个文档目前只是个草稿格式,随着 Python3.9 的正式发布,一些特性可能还会添加或删除。下面我们看看语言上的变化。

推荐阅读

添加微信[gopython3].回复:回复 Go 或者 Python 加对应技术群。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值