2021年5月21日 星期五

[ Python 文章收集 ] How Python 3.9 fixed decorators and improved dictionaries

 Source From Here

Preface
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:
  1. def process_pricing_line(line):  
  2.     if line.startswith("pricing:"):  
  3.         return line[len("pricing:"):]  
  4.     return line  
  5. process_pricing_line("pricing:20")  
Output:
'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:")
'20'

>>> "20".lstrip("pricing:")
'20'

Arbitrary decorator expressions
Previously, the rules about which expressions are allowed in a decorator were underdocumented and hard to understand. For example, while:
  1. @item.thing  
  2. def foo():  
  3.     pass  
is valid, and:
  1. @item.thing()  
  2. def foo():  
  3.     pass  
is valid, the similar:
  1. @item().thing  
  2. def foo():  
  3.     pass  
produces a syntax error.

Starting in Python 3.9, any expression is valid as a decorator:
  1. from unittest import mock  
  2.   
  3. item = mock.MagicMock()  
  4.   
  5. @item().thing  
  6. def foo():  
  7.     pass  
  8. print(item.return_value.thing.call_args[0][0])  
Output:
<function foo at 0x7f3733897040>


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...