I have just found that Python has a new operator named "Walrus", it's so interesting to deep dive and worth writing down:

Codeblock Description:

  • Prompts the user to enter 0, 1, or 2.
  • If the user enters something else, it keeps asking.
  • As soon as the input is valid, the loop ends.

The original code:

list_embedding_models = [
        "0-Ollama-Nomic Embedded", 
        "1-OpenAI Embedding", 
        "2-Chroma DefaultEmbeddingFunction"
    ]
print(f"====Select an Embedding model:")
    print(*list_embedding_models, sep="\n")

while True:
    embedding_model_choice = input("Please enter 0,1, or 2: ")
    if embedding_model_choice in {"0", "1", "2"}:
        break
    else:
        print("Try again!")

Then we can apply Walrus Operator ':='

list_embedding_models = [
        "0-Ollama-Nomic Embedded",
        "1-OpenAI Embedding",
        "2-Chroma DefaultEmbeddingFunction"
    ]
print(f"====Select an Embedding model:")
    print(*list_embedding_models, sep="\n")
    while (embedding_model_choice := input("Please enter 0,1, or 2: ")) not in {"0", "1", "2"}: print("Try again!")
    print(embedding_model_choice)
    print(f"==> User choose {list_embedding_models[int(embedding_model_choice)]}")

What's happening?

  • embedding_model_choice := input(...) this assigns the result of input() to embedding_model_choice, inside the condition of the while loop.
  • not in {"0", "1", "2"}: then checks whether the user's input is one of the allowed choices. If not, it loops again.
  • print("Try again!"): if the user's input is invalid, it will print a message Try again! and ask for input again. In this step, you can either print a message or pass it.
while (embedding_model_choice := input("Please enter 0,1, or 2: ")) not in {"0", "1", "2"}: pass

Use case:

  • Cleaner, shorter loops when you want to assign and check a value in the same place.
  • Useful in input loops, file reading, etc.

Risk:

  • The walrus operator is a new syntax that is available from Python 3.8 and later.
  • If your code needs to support legacy systems, then it will be broken, so it's better to use the classic while ... if ... break.