Aug 13, 2019

[python] some new features in 3.8

Reference:
https://lwn.net/Articles/793818/

walrus operator (:=, like in Go, but also works in 'while' statement):

code:
if m := re.match(p1, line):
        return m.group(1)
elif m := re.match(p2, line):
    return m.group(2)
elif m := re.match(p3, line):
while ent := obj.next_entry():

    ... # process ent

Debug support for f-strings (the format string):

code:
Before 3.8:
print(f'foo={foo} bar={bar}')

In 3.8:
>>> foo = 42
>>> bar = 'answer ...'
>>> print(f'{foo=} {bar=}')
foo=42 bar=answer ...

"!s" uses the str() representation, rather than the default repr() value:

code:
>>> import datetime
>>> now = datetime.datetime.now()
>>> print(f'{now=} {now=!s}')
now=datetime.datetime(2019, 7, 16, 16, 58, 0, 680222) now=2019-07-16 16:58:00.680222

"!f" will be available to access formatting controls:

code:
>>> import math
>>> print(f'{math.pi=!f:.2f}')
math.pi=3.14

Positional-only parameters:

Before 3.8 we can't make a pure python function likes the built-in ones
which disallows keyword arguments.

In 3.8, the "/" denotes the end of the positional-only parameters in an argument list.

code:
def fun(a, b, /, c, d, *, e, f):
thus:
fun(1, 2, 3, 4, e=5, f=6)          # legal
fun(1, 2, 3, d=4, e=5, f=6)        # legal
fun(a=1, b=2, c=3, d=4, e=5, f=6)  # illegal

A movable __pycache__:

__pycache__ directory is created by the Python 3 interpreter (starting with 3.2) to hold .pyc files.

PYTHONPYCACHEPREFIX environment variable (also accessible via the -X pycache_prefix=PATH command-line flag) to point the interpreter elsewhere for storing those files.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.