Python 3.7.0 正式版发布,新特性翻译
美国时间6月27日晚8点,Python 3.7.0 经过多轮测试,终于发布了正式版,增强了多处特性功能,同时 3.6 也更新到 3.6.6 稳定版本。
主要特性
- PEP 539,新增 CPython 中用于线程本地存储的 C-API
- PEP 545,Python 官方文档翻译版本,新增日文、法文、韩文
- PEP 552,优化 pyc 文件
- PEP 553,新增内置函数
breakpoint()
,该函数在调用时自动进入调试器 - PEP 557,新增内置模块
dataclasses
,可大幅简化类实例属性的初始化定义 - PEP 560,新增支持类型模块和泛型
- PEP 562,支持在模块定义
__getattr__
和__dir__
- PEP 563,推迟对注释语句的分析从而优化 Python 的类型提示
- PEP 564,
time
内置函数支持纳秒 - PEP 565,重新在 __main__ 中默认显示 DeprecationWarning
- PEP 567,新增
contextvars
模块,可实现上下文变量解决变量线程安全 - 避免使用 ASCII 作为默认文本编码,强制 UTF-8 编码运行
- 字典对象的 keys 按插入顺序排列,现在是官方语言规范
- 多方面的显著性能优化
dataclasses
模块 示例
这个特性可能是 3.7.0 以后比较常用的了,是从其他语言借鉴过来的,这里简单演示下用法。
假如我们要封装一个类对象,在之前我们的代码可能要这么写:
class Article(object): def __init__(self, _id, author_id, title, text, tags=None, created=datetime.now(), edited=datetime.now()): self._id = _id self.author_id = author_id self.title = title self.text = text self.tags = list() if tags is None else tags self.created = created self.edited = edited if type(self.created) is str: self.created = dateutil.parser.parse(self.created) if type(self.edited) is str: self.edited = dateutil.parser.parse(self.edited) def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return (self._id, self.author_id) == (other._id, other.author_id) def __lt__(self, other): if not isinstance(other, self.__class__): return NotImplemented return (self._id, self.author_id) < (other._id, other.author_id) def __repr__(self): return '{}(id={}, author_id={}, title={})'.format( self.__class__.__name__, self._id, self.author_id, self.title)
大量的初始化属性要定义默认值,可能还需要重写一堆魔法方法,来实现类实例之间的排序 去重 等功能。
如果使用dataclass
进行改造,可以写成这个样子:
@dataclass(order=True) class Article(object): _id: int author_id: int title: str = field(compare=False) text: str = field(repr=False, compare=False) tags: List[str] = field(default=list(), repr=False, compare=False) created: datetime = field(default=datetime.now(), repr=False, compare=False) edited: datetime = field(default=datetime.now(), repr=False, compare=False) def __post_init__(self): if type(self.created) is str: self.created = dateutil.parser.parse(self.created) if type(self.edited) is str: self.edited = dateutil.parser.parse(self.edited)
可见这种语法使代码更加简练清晰,也更符合面向对象思想的语法方式,用过 SQLAlchemy 的同学肯定觉得很像 ORM 写法。
上述示例只是最基础的展示,更丰富的用法可以查看PEP 557文档。
3.7.0 下载地址
Python Release Python 3.7.0 www.python.org
更多特性
What’s New In Python 3.7 docs.python.org
原文地址:https://zhuanlan.zhihu.com/p/38609120
相关推荐
-
python异常处理的哲学 python基础
2019-9-2
-
Python存储系统(Redis) python基础
2019-10-9
-
用Python做自己的2020专属Flag动图 python基础
2020-6-17
-
深入学习python解析并读取PDF文件内容的方法 python基础
2019-7-21
-
用 Python 脚本,监听附近网络 Wi-Fi 设备,通过邮件和微信进行消息推送 python基础
2019-2-24
-
Pandas速查手册中文 python基础
2019-8-25
-
Jupyter Notebook 使用小记 python基础
2019-7-25
-
堆排序的Python实现(附详细过程图和讲解) python基础
2019-1-29
-
【Python3】Python模块与包的导入 python基础
2019-4-27
-
机器学习之决策树算法 python基础
2019-10-8