mirror of
https://github.com/LCTT/TranslateProject.git
synced 2024-12-23 21:20:42 +08:00
translated
This commit is contained in:
parent
17e16ae521
commit
c22f2f7f9a
@ -1,130 +0,0 @@
|
||||
[#]: subject: (How Python 3.9 fixed decorators and improved dictionaries)
|
||||
[#]: via: (https://opensource.com/article/21/5/python-39-features)
|
||||
[#]: author: (Moshe Zadka https://opensource.com/users/moshez)
|
||||
[#]: collector: (lujun9972)
|
||||
[#]: translator: (geekpi)
|
||||
[#]: reviewer: ( )
|
||||
[#]: publisher: ( )
|
||||
[#]: url: ( )
|
||||
|
||||
How Python 3.9 fixed decorators and improved dictionaries
|
||||
======
|
||||
Explore some of the useful features of the recent version of Python.
|
||||
![Python in a coffee cup.][1]
|
||||
|
||||
This is the tenth in a series of articles about features that first appeared in a version of Python 3.x. Some of these versions have been out for a while. Python 3.9 was first released in 2020 with cool new features that are still underused. Here are three of them.
|
||||
|
||||
### Adding dictionaries
|
||||
|
||||
Say you have a dictionary with "defaults," and you want to update it with parameters. Before Python 3.9, the best option was to copy the defaults dictionary and then use the `.update()` method.
|
||||
|
||||
Python 3.9 introduced the union operator to dictionaries:
|
||||
|
||||
|
||||
```
|
||||
defaults = dict(who="someone", where="somewhere")
|
||||
params = dict(where="our town", when="today")
|
||||
defaults | params
|
||||
|
||||
```
|
||||
```
|
||||
` {'who': 'someone', 'where': 'our town', 'when': 'today'}`
|
||||
```
|
||||
|
||||
Note that the order matters. In this case, the `where` value from `params` overrides the default, as it should.
|
||||
|
||||
### Removing prefixes
|
||||
|
||||
If you have done ad hoc text parsing or cleanup with Python, you will have written code like:
|
||||
|
||||
|
||||
```
|
||||
def process_pricing_line(line):
|
||||
if line.startswith("pricing:"):
|
||||
return line[len("pricing:"):]
|
||||
return line
|
||||
process_pricing_line("pricing:20")
|
||||
|
||||
```
|
||||
```
|
||||
` '20'`
|
||||
```
|
||||
|
||||
This kind of code is prone to errors. For example, if the string is copied incorrectly to the next line, the price will become `0` instead of `20`, and it will happen silently.
|
||||
|
||||
Since Python 3.9, strings have a `.lstrip()` method:
|
||||
|
||||
|
||||
```
|
||||
`"pricing:20".lstrip("pricing:")`[/code] [code]` '20'`
|
||||
```
|
||||
|
||||
### Arbitrary decorator expressions
|
||||
|
||||
Previously, the rules about which expressions are allowed in a decorator were underdocumented and hard to understand. For example, while:
|
||||
|
||||
|
||||
```
|
||||
@item.thing
|
||||
def foo():
|
||||
pass
|
||||
```
|
||||
|
||||
is valid, and:
|
||||
|
||||
|
||||
```
|
||||
@item.thing()
|
||||
def foo():
|
||||
pass
|
||||
```
|
||||
|
||||
is valid, the similar:
|
||||
|
||||
|
||||
```
|
||||
@item().thing
|
||||
def foo():
|
||||
pass
|
||||
```
|
||||
|
||||
produces a syntax error.
|
||||
|
||||
Starting in Python 3.9, any expression is valid as a decorator:
|
||||
|
||||
|
||||
```
|
||||
from unittest import mock
|
||||
|
||||
item = mock.MagicMock()
|
||||
|
||||
@item().thing
|
||||
def foo():
|
||||
pass
|
||||
print(item.return_value.thing.call_args[0][0])
|
||||
|
||||
```
|
||||
```
|
||||
` <function foo at 0x7f3733897040>`
|
||||
```
|
||||
|
||||
While keeping to simple expressions in the decorator line is still a good idea, it is now a human decision, rather than the Python parser's option.
|
||||
|
||||
### Welcome to 2020
|
||||
|
||||
Python 3.9 was released about one year ago, but some of the features that first showed up in this release are cool—and underused. Add them to your toolkit if you haven't already.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://opensource.com/article/21/5/python-39-features
|
||||
|
||||
作者:[Moshe Zadka][a]
|
||||
选题:[lujun9972][b]
|
||||
译者:[译者ID](https://github.com/译者ID)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://opensource.com/users/moshez
|
||||
[b]: https://github.com/lujun9972
|
||||
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/coffee_python.jpg?itok=G04cSvp_ (Python in a coffee cup.)
|
@ -0,0 +1,130 @@
|
||||
[#]: subject: (How Python 3.9 fixed decorators and improved dictionaries)
|
||||
[#]: via: (https://opensource.com/article/21/5/python-39-features)
|
||||
[#]: author: (Moshe Zadka https://opensource.com/users/moshez)
|
||||
[#]: collector: (lujun9972)
|
||||
[#]: translator: (geekpi)
|
||||
[#]: reviewer: ( )
|
||||
[#]: publisher: ( )
|
||||
[#]: url: ( )
|
||||
|
||||
Python 3.9 如何修复装饰器并改进字典
|
||||
======
|
||||
探索最近版本的 Python 的一些有用的特性。
|
||||
![Python in a coffee cup.][1]
|
||||
|
||||
这是关于首次出现在 Python 3.x 版本中的特性的系列文章中的第十篇,其中一些版本已经发布了一段时间。Python 3.9 在 2020 年首次发布,具有很酷的新特性,但仍未被充分利用。下面是其中的三个。
|
||||
|
||||
### 添加字典
|
||||
|
||||
假设你有一个 “defaults” 字典,而你想更新它的参数。在 Python 3.9 之前,最好的办法是复制 defaults 字典,然后使用 `.update()` 方法。
|
||||
|
||||
Python 3.9 为字典引入了联合运算符:
|
||||
|
||||
|
||||
```
|
||||
defaults = dict(who="someone", where="somewhere")
|
||||
params = dict(where="our town", when="today")
|
||||
defaults | params
|
||||
|
||||
```
|
||||
```
|
||||
` {'who': 'someone', 'where': 'our town', 'when': 'today'}`
|
||||
```
|
||||
|
||||
注意,顺序很重要。在这种情况下,来自 `params` 的 `where ` 值覆盖了默认值,因为它应该如此。
|
||||
|
||||
### 删除前缀
|
||||
|
||||
如果你用 Python 做了临时的文本解析或清理,你会写出这样的代码:
|
||||
|
||||
|
||||
```
|
||||
def process_pricing_line(line):
|
||||
if line.startswith("pricing:"):
|
||||
return line[len("pricing:"):]
|
||||
return line
|
||||
process_pricing_line("pricing:20")
|
||||
|
||||
```
|
||||
```
|
||||
` '20'`
|
||||
```
|
||||
|
||||
这样的代码很容易出错。例如,如果字符串被错误地复制到下一行,价格就会变成 `0` 而不是 `20`,而且会悄悄地发生。
|
||||
|
||||
从 Python 3.9 开始,字符串有了一个 `.lstrip()` 方法:
|
||||
|
||||
|
||||
```
|
||||
`"pricing:20".lstrip("pricing:")`[/code] [code]` '20'`
|
||||
```
|
||||
|
||||
### 任意的装饰器表达式
|
||||
|
||||
以前,关于装饰器中允许哪些表达式的规则没有得到充分的记录,而且很难理解。例如:虽然
|
||||
|
||||
|
||||
```
|
||||
@item.thing
|
||||
def foo():
|
||||
pass
|
||||
```
|
||||
|
||||
是有效的,而且:
|
||||
|
||||
|
||||
```
|
||||
@item.thing()
|
||||
def foo():
|
||||
pass
|
||||
```
|
||||
|
||||
是有效的,相似地:
|
||||
|
||||
|
||||
```
|
||||
@item().thing
|
||||
def foo():
|
||||
pass
|
||||
```
|
||||
|
||||
产生一个语法错误。
|
||||
|
||||
从 Python 3.9 开始,任何表达式作为装饰器都是有效的:
|
||||
|
||||
|
||||
```
|
||||
from unittest import mock
|
||||
|
||||
item = mock.MagicMock()
|
||||
|
||||
@item().thing
|
||||
def foo():
|
||||
pass
|
||||
print(item.return_value.thing.call_args[0][0])
|
||||
|
||||
```
|
||||
```
|
||||
` <function foo at 0x7f3733897040>`
|
||||
```
|
||||
|
||||
虽然在装饰器中保持简单的表达式仍然是一个好主意,但现在是人类的决定,而不是 Python 分析器的选择。
|
||||
|
||||
### 欢迎来到 2020 年
|
||||
|
||||
Python 3.9 大约在一年前发布,但在这个版本中首次出现的一些特性非常酷,而且没有得到充分利用。如果你还没使用,那么将它们添加到你的工具箱中。
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://opensource.com/article/21/5/python-39-features
|
||||
|
||||
作者:[Moshe Zadka][a]
|
||||
选题:[lujun9972][b]
|
||||
译者:[geekpi](https://github.com/geekpi)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://opensource.com/users/moshez
|
||||
[b]: https://github.com/lujun9972
|
||||
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/coffee_python.jpg?itok=G04cSvp_ (Python in a coffee cup.)
|
Loading…
Reference in New Issue
Block a user