New Features
Last updated
Last updated
Suppose you are doing a RSA challenge. Your objective is to factor and you want the values of and printed out if the factorization algorithm succeeded. In this case, the code snippet will look like this:
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:
Output:
Here print(f"{hex(leaked_address) = }")
expands to print(f"hex(leaked_address) = {hex(leaked_address)}")
.
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:
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:
In order to achieve the above semantics with correct syntax, using the walrus operator:
Using walrus operator as a normal assignment operator results in a syntax error unless you put parentheses around it.