• Introduction to the
  • Walrus expression :=
  • Only positional argument /
  • The f-strings specifier is equal to
  • Start the asynchronous REPL
  • Unittest supports asynchrony

Introduction to the

Python3.8 has been released. See What’s New In Python3.8 for official documentation.

Introduces some of the new features in Python3.8.

Walrus expression :=

The new syntax := will assign a value to a variable that is part of a larger expression.

if (n := len(a)) > 10:
  print(f"List is too long ({n} elements, expected <= 10)")
Copy the code

For if judgments, avoid calling len() twice.

discount = 0.0
if (mo := re.search(r'(\d+)% discount', advertisement)):
  discount = float(mo.group(1)) / 100.0
Copy the code

When the regular expression matches and gets the result.

# Loop over fixed length blocks
while (block := f.read(256)) != ' ':
  process(block)
Copy the code

Used in a while loop to evaluate simultaneously and determine whether it is null.

[clean_name.title() for name in names
 if (clean_name := normalize('NFC', name)) in allowed_names]
Copy the code

Used in list derivation.

See PEP 572 for a complete introduction.

Only positional argument /

New function argument syntax/specifies that some function arguments must be specified as positional arguments and cannot be used as keyword arguments.

def f(a, b, /, c, d, *, e, f):
  print(a, b, c, d, e, f)
Copy the code

In the example above, a and B are positional only arguments, c and D can be both positional and keyword arguments, and e and f must be keyword arguments.

>>> def f(a, b, /, **kwargs):
.    print(a, b, kwargs)
...
>>> f(10.20, a=1, b=2, c=3)         # a and b are used in two ways
10 20 {'a': 1.'b': 2.'c': 3}
Copy the code

Only positional parameter names are still available in **kwargs.

class Counter(dict):
  def __init__(self, iterable=None, /, **kwds):
    # Note "iterable" is a possible keyword argument
Copy the code

See PEP 570 for a complete introduction.

The f-strings specifier is equal to

F-strings adds the = specifier, and f'{expr=}’ will be expanded to the text of the expression, plus an equal sign, and the result of executing the expression.

>>> user = 'eric_idle'
>>> member_since = date(1975.7.31)
>>> f'{user=} {member_since=}'
"user='eric_idle' member_since=datetime.date(1975, 7, 31)"
Copy the code

Start the asynchronous REPL

To start an asynchronous REPL with Python -m asyncio, you can use await directly at the top-level level instead of wrapping it in functions.

Unittest supports asynchrony

import unittest

class TestRequest(unittest.IsolatedAsyncioTestCase):

    async def asyncSetUp(self):
        self.connection = await AsyncConnection()

    async def test_get(self):
        response = await self.connection.get("https://example.com")
        self.assertEqual(response.status_code, 200)

    async def asyncTearDown(self):
        await self.connection.close()


if __name__ == "__main__":
    unittest.main()
Copy the code