Python3.12 新增内容

https://medium.com/techtofreedom/5-handy-python-3-12-new-features-that-improve-your-coding-experience-fe2d6e1f05b4

  • 类型系统,更方便的类型别名声明方式

简便的类型别名声明

我们可以直接如下定义类型别名

Point = tuple[float, float]

class PointTest:
	def __init__(self):
		self.point: Point = (0, 0)

在python12中,可以用type对这种别名进行表示和区分

type Point = tuple[float, float]

class PointTest:
	def __init__(self):
		self.point: Point = (0, 0)

TypedDict和Unpack的结合:更精准的**kwargs传参

Python38时引入了TypedDict,用于显示定义dict的键值类型。

from typing import TypedDict

class Person(TypedDict):
    name: str
    age: int

def get_author(author: Person):
    print(author)

author_data = {'name': 'Yang', 'age': 30, 'gender': 'male'}
get_author(author_data)

然而,若将参数中的author替换为**kwargs,程序就会报错。

from typing import TypedDict

class Person(TypedDict):
    name: str
    age: int

# def get_author(author: Person):
#     print(author)

def get_author(**kwargs: Person):
    print(author)

author_data = {'name': 'Yang', 'age': 30, 'gender': 'male'}
get_author(author_data)

因为,所有的参数就会被当做Person类型,而不是将所有参数当做一个Person的子类。

因此,python3.12提供了Unpack类型。

改进的F-String语法。

可以在F-String中的括号中直接使用双引号。

>>> print(f"This is the author: {"".join(["Y","a","n","g"])}")
This is the author: Yang

另外,还可以使用反斜杠了。

>>> print(f"This is the author:\n{"".join(["Y","a","n","g"])}")
Traceback (most recent call last):
  ...
  File "<input>", line 1
    print(f"This is the author:\n{"".join(["Y","a","n","g"])}")
                                            ^
SyntaxError: f-string: expecting '}'

now:

>>> print(f"This is the author:\n{"".join(["Y","a","n","g"])}")
This is the author:
Yang

提供Override装饰器,显示声明函数实现覆盖

from typing import override

class Animal:
	def speak(self) -> str:
		pass

class Dog(Animal):
	@override
	def speak(self) -> str:
		return 'woof'

	def walk(self) -> str:
		return 'walking'

my_dog: Dog = Dog()
print(my_dog.speak())
# woof
print(my_dog.walk())

报错信息能提供建议

当然,建议仅针对NameErrorImportErrorSyntaxError异常

posted @ 2023-12-24 15:39  ckxkexing  阅读(12)  评论(0编辑  收藏  举报