Skip to content

Instantly share code, notes, and snippets.

@Mhs-220
Last active July 4, 2020 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mhs-220/2db6501173925c0894ec86100590172c to your computer and use it in GitHub Desktop.
Save Mhs-220/2db6501173925c0894ec86100590172c to your computer and use it in GitHub Desktop.
You Probably Don't Know Python - Part 2
# Without Walrus Operator
n = len("Hello, World")
if n > 10:
print(f"WoW, {n} is Tooooo Large!")
# With Walrus Operator
if (n := len("Hello, World")) > 10:
print(f"WoW, {n} is Tooooo Large!")
# Without Walrus Operator
[normalize('NFC', name).title() for name in names
if normalize('NFC', name) in allowed_names]
# With Walrus Operator
[clean_name.title() for name in names
if (clean_name := normalize('NFC', name)) in allowed_names]
# Without Walrus Operator
with open('my-binary', 'rb') as myfile:
while True:
block = myfile.read(128)
if block == '':
break
do_something(block)
# Without Walrus, But Smarter
from functools import partial
with open('my-binary', 'rb') as myfile:
for block in iter(partial(myfile.read, 128), b''):
do_something(block)
# With Walrus Operator
with open('my-binary', 'rb') as myfile:
while (block := myfile.read(128)) != '':
do_something(block)
from datetime import datetime
a_float = 0.854623
a_string = "Joe"
today = datetime(year=2020, month=7, day=4)
width = 10
precision = 4
value = 12.3456789
print(f"Hello, {a_string!r}") # Hello, 'Joe'
print(f"{a_string} height is {a_float * 100:.0f}") # Joe height is 85
print(f"Download Progress is {a_float:%}") # Download Progress is 85.462300%
print(f"Today is {today:%B %d, %Y}") # Today is July 04, 2020
print(f"Result: {value:{width}.{precision}}") # Result: 12.35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment