Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python underscore as a function parameter

I have a python specific question. What does a single underscore _ as a parameter means? I have a function calling hexdump(_). The _ was never defined, so I guess it has some special value, I could not find a reference telling me what it means on the net. I would be happy if you could tell me.

like image 735
Steve Avatar asked Apr 26 '11 07:04

Steve


People also ask

Why do we use __ in Python?

The Python interpreter modifies the variable name with ___. So Multiple times It uses as a Private member because another class can not access that variable directly. The main purpose for __ is to use variable /method in class only If you want to use it outside of the class you can make it public.

What is difference between _ and __ in Python?

Enforced by the Python interpreter. Double Leading and Trailing Underscore( __var__ ): Indicates special methods defined by the Python language. Avoid this naming scheme for your own attributes. Single Underscore( _ ): Sometimes used as a name for temporary or insignificant variables (“don't care”).

What is _ parameter in Python?

The terms parameter and argument can be used for the same thing: information that are passed into a function. From a function's perspective: A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that is sent to the function when it is called.

Can variables start with _ in Python?

Rules for Python variables: A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )


2 Answers

From what I've been able to figure out, it seems like this is the case:

_ is used to indicate that the input variable is a throwaway variable/parameter and thus might be required or expected, but will not be used in the code following it.

For example:

# Ignore a value of specific location/index  for _ in range(10)      print("Test")    # Ignore a value when unpacking  a,b,_,_ = my_method(var1)  

(Credit to this post)

The specific example I came across was this:

    def f(_):         x = random() * 2 - 1         y = random() * 2 - 1         return 1 if x ** 2 + y ** 2 < 1 else 0 
like image 81
Marco Avatar answered Sep 22 '22 15:09

Marco


In Python shells, the underscore (_) means the result of the last evaluated expression in the shell:

>>> 2+3
5
>>> _
5

There's also _2, _3 and so on in IPython but not in the original Python interpreter. It has no special meaning in Python source code as far as I know, so I guess it is defined somewhere in your code if it runs without errors.

like image 38
Tamás Avatar answered Sep 23 '22 15:09

Tamás