编写地道的 Python 代码
你需要先深入理解 Python,才能编写出地道的、符合Python 风格的代码。
但这到底是什么意思呢?
以下是一些例子
虚假与真实
几乎所有数据类型都可以解释为布尔值。空列表?假值。三个字符的字符串?真值。
# Instead of writing something like this
a = [1, 2, 3]
if len(a) > 0:
...
# You could write:
a = [1, 2, 3]
if a:
...
三元运算符
Python 确实有一个三元运算符,它利用了单行 𝚒𝚏s:
# Instead of the lenghty version
a = True
value = 0
if a:
value = 1
# You could shorten it to:
a = True
value = 1 if a else 0
链式比较运算符
Python 语法应该尽可能简单。这就是为什么你可以使用类似数学的符号,例如这样。
𝟻 < 𝚡 < 𝟷𝟶
# Instead of this
if x < 10 and x > 5:
...
# you can write this
if 5 < x < 10:
...
多重任务和解构任务
你可以在同一行 Python 代码中赋值不同的变量。
# Instead of writing
x = 'foo'
y = 'foo'
z = 'foo'
# or
a = [1, 2, 3]
x = a[0]
y = a[1]
z = a[2]
# you could simplify to:
x = y = z = 'foo'
# and
a = [1, 2, 3]
x, y, z = a
f 弦
f-strings 在 Python 内部提供了一种类似模板的迷你语言。例如,你可以用它来对齐文本,或者指定float字符串的精度。
username = "Bas"
monthly_price = 9.99
# Instead of transforming each element,
print(username.rjust(10), '|', "{:3.2f}".format(monthly_price))
# you can use a single f-string
print(f"{username : >10} | {monthly_price:3.2f}")
列表推导式/字典推导式
列表和字典推导式或许是最具 Pythonic 风格的特性。它们在修改数据结构时非常有用。
usernames = ["alice", "bas", "carol"]
# Instead of a loop:
users_with_a = []
for username in usernames:
if username.startswith("a"):
users_with_a.append(username)
# Use a list comprehension
users_with_a = [username for username in usernames if username.startswith("a")]
# Same for dicts: Instead of a loop
users_dict = {}
for username in usernames:
users_dict[username] = get_user_id(username)
# you can use dict comprehensions
users_dict = {username: get_user_id(username) for username in usernames}
in关键词
Python 有一个in可以作用于集合(例如列表)的操作符。
你可以用它来检查某个元素是否在选项列表中。
name = 'Alice'
found = False
if name == 'Alice' or name == 'Bas' or name == 'Carol':
...
name = 'Alice'
if city in {'Alice', 'Bas', 'Carol'}:
...
enumerate
当你不仅需要通过列表访问每个元素,还需要在循环中使用计数器时,你可以使用enumerate
a = ["A", "B", "C"]
# Instead of using an index variable
for i in range(len(a)):
print(i, a[i])
# you could iterate the list as usual and attach a counter
for counter, letter in enumerate(a):
print(counter, letter)
海象操作员
Python 3.8 引入了海象运算符,它允许你使用赋值表达式。
这意味着你可以在同一行中给一个变量赋值并访问该值。
n = len(a)
if n > 10:
print(f"List is too long ({n} elements, expected <= 10)")
if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")
assert
在代码中使用断言不仅可以提高安全性,还有助于理解特定代码行背后的逻辑。
# Instead of a comment
def activate_user(user):
# User has to be a `UserModel` object
user.active = True
user.save()
# you can use assert
def activate_user(user):
assert type(user, UserModel)
user.active = True
user.save()
模式匹配
模式匹配是 Python 3.10 中新增的一项非常实用的功能。
我三月份在推特上就此话题发过一条推文:
你认为哪些是Python的惯用写法?
分享你的想法!💡👋
文章来源:https://dev.to/bascodes/writing-idiomatic-python-code-1ehe