What is the := operator?

This is a new operator that is coming to Python 3.8 and actually had a role in BDFL Guido van Rossum's early retirement.

Formally, the operator allows what's called an "assignment expression". Informally, the operator is referred to as the "walrus operator".

It allows assignment while also evaluating an expression.

So this:

env_base = os.environ.get("PYTHONUSERBASE", None)
if env_base:
    return env_base

can be shortened to:

if env_base := os.environ.get("PYTHONUSERBASE", None):
    return env_base

https://www.python.org/dev/peps/pep-0572/#examples-from-the-python-standard-library


In all languages that support an operator := it means assignment.

  • In languages that support an operator :=, the = operator usually means an equality comparison.
  • In languages where = means assignment, == is typically used for equality comparison.

does := mean =?

I can't recall any languages where := means the same as =.


In MySQL := and = are both used for assignment, however they are not interchangeable and selecting the correct one depends on the context. To make matters more confusing the = operator is also used for comparison. The interpretation of = as either assignment or comparison also depends on context.