Home > Enterprise >  Underscore variable with walrus operator in Python
Underscore variable with walrus operator in Python

Time:06-16

In Python, the variable name _ (underscore) is often used for throwaway variables (variables that will never be used, hence do not need a proper name).

With the walrus operator, :=, I see the need for a variable that is rather short lived (used in say only one line of code). I wonder if the use of _ is reasonable to use also in this case, or if it might be confusing for someone reading the code?

Example:

a = (dummy := pd.Series([1, 2, 3, 4, 5]))[dummy > 2]

Here a pandas series is created and immediately filtered. The name dummy could in my opinion be replaced with _:

a = (_ := pd.Series([1, 2, 3, 4, 5]))[_ > 2]

CodePudding user response:

I think it isn't enough reasonable to use underline because it has already been used twice in the code.

Even if you don't use the dummy variable anymore, it's less readable in the code now.

CodePudding user response:

You are using the variable dummy, to filter the series. Therefore, don't replace it with _.

  • Related