Skip to content

Instantly share code, notes, and snippets.

@mpkocher
Last active May 9, 2020 21:35
Show Gist options
  • Save mpkocher/e5b2e69997f5ca84cad22257568ef8c2 to your computer and use it in GitHub Desktop.
Save mpkocher/e5b2e69997f5ca84cad22257568ef8c2 to your computer and use it in GitHub Desktop.
Exploring Py 3.8 Walrus + F-string Tweet By Raymond Hettinger
#!/usr/bin/env python3
"""
Requires Python 3.8
Expanding on a Tweet from RH using walrus and f-strings
https://twitter.com/raymondh/status/1153085050650423296
"""
import logging
import os
import sys
from math import radians, sin
log = logging.getLogger(__name__)
FUNCS = []
def register(f):
FUNCS.append(f)
def w(*args, **kwargs):
return f(*args, **kwargs)
return w
@register
def example_rh_tweet():
"""Raw example from RH to show usage of := (walrus) with f-strings"""
# Note that \N means look up the unicode by id here. e.g., \N{Greek Capital Letter Theta}
# https://en.wikipedia.org/wiki/List_of_Unicode_characters
n = 4
for angle in range(4):
log.info(f'{angle=}\N{degree sign} {(theta:=radians(angle))=:.3f} {sin(theta)=:.3f}')
@register
def example_02():
"""
Notice this also works outside of a loop.
"""
angle = 90.0
log.info(f'{angle=}\N{degree sign} {(theta:=radians(angle))=:.3f} {sin(theta)=:.3f}')
log.info(theta)
@register
def example_03():
"""
Calling the raw function call outside of the f-string.
Note, the parentheses are extremely important
"""
angle = 90.0
# This is a SyntaxError
# theta := radians(angle)
# This is valid python 3.8
(theta := radians(angle))
log.info(f"Theta={theta}")
log.info(f'{angle=}\N{degree sign} {theta=:.3f} {sin(theta)=:.3f}')
log.info(theta)
@register
def example_04():
"""
Values defined within the f-string don't need to be used within the f-string.
"""
angle = 90.0
log.info(f'{angle=}\N{degree sign} {(theta:=radians(angle))=:.3f} {(sin_theta:=sin(theta))=:.3f}')
log.info(f'{theta=}')
log.info(f'{sin_theta=}')
def run_func(func):
print("Running func {}".format(func.__name__))
return func()
def run_main():
_ = logging.basicConfig(level=logging.INFO, stream=sys.stdout)
_ = list(map(run_func, FUNCS))
return 0
if __name__ == '__main__':
sys.exit(run_main())
@rkennesson
Copy link

rkennesson commented May 9, 2020

for anyone who was confused, the "reverse walrus" (=:) is really just a combination of two operators or language features. f-string formatting[1] (float in this case, theta:.3f) and the new self documenting expression[2] (theta=).

for example log.info(f'{angle=}\N{degree sign} {theta=:.3f} {sin(theta)=:.3f}') from line 65 can be rewritten as

log.info(f'angle={angle}\N{degree sign} theta={theta:.3f} sin(theta)={sin(theta):.3f}')

top/bottom comparison

log.info(f'{angle=}\N{degree sign} {theta=:.3f} {sin(theta)=:.3f}')
log.info(f'angle={angle}\N{degree sign} theta={theta:.3f} sin(theta)={sin(theta):.3f}')

[1] https://www.python.org/dev/peps/pep-0498/#format-specifiers

[2] https://docs.python.org/3/whatsnew/3.8.html#f-strings-support-for-self-documenting-expressions-and-debugging

[3] BONUS: https://docs.python.org/3.3/howto/unicode.html#the-string-type \N lookup examples from python docs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment