New Features

f-string Debugging

Suppose you are doing a RSA challenge. Your objective is to factor N=pqN = p * q and you want the values of pp and qq printed out if the factorization algorithm succeeded. In this case, the code snippet will look like this:

p = 13
q = 37
print(f"{p = }")
print(f"{q = }")

Output:

Here print(f"{p = }") expands to print(f"p = {p}") .

Suppose you are doing a ret2libc challenge and you have just leaked an address from libc. Now you want to examine this address in hex and see if it looks legit. In this case, the code snippet will look like this:

leaked_address = 13371337
print(f"{hex(leaked_address) = }")

Output:

Here print(f"{hex(leaked_address) = }") expands to print(f"hex(leaked_address) = {hex(leaked_address)}") .

Walrus Operator

The := operator is officially known as the assignment expression operator. During early discussions, it was dubbed the walrus operator because the := syntax resembles the eyes and tusks of a sideways walrus:

To get a first impression of what assignment expressions are all about, start your REPL and play around with the following code:

>>> walrus = False
>>> walrus
False

>>> (walrus := True)
True
>>> walrus
True

There's a subtle—but important—difference between the two types of assignments seen earlier with the walrus variable. An assignment expression returns the value, while a traditional assignment doesn't. You can see this in action when the REPL doesn't print any value after walrus = False on line 1, while it prints out True after the assignment expression on line 5.

Why is walrus operator useful? Consider the following example:

# Syntax error
while line=file.readline():
    print(line)

In order to achieve the above semantics with correct syntax, using the walrus operator:

# Walrus operator
while (line:=file.readline()):
    print(line)

Using walrus operator as a normal assignment operator results in a syntax error unless you put parentheses around it.

Reference

Last updated