1

Can somebody explain me the function of _, in Python? I found this in the following codesnipped.

@property
def frame(self):
    if self._enteredFrame and self._frame is None:
        _, self._frame = self._capture.retrieve (channel = self.channel)
        return self._frame

I never saw this before.

m harms
  • 13
  • 5

2 Answers2

1

_ is a variable name.

self._capture.retrieve returns a seqeunce with 2-elements, and the following statement assign the first element to _, and the second element to self._frame. (tuple unpacking)

_, self._frame = self._capture.retrieve(channel=self.channel)

Conventionally, _ is used to ignore the value.

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • I understand that _, is not one thing, but _ and , So maybe better writen like _ ; self._frame = .... – m harms Jan 03 '15 at 12:34
  • @mharms, If you replace `,` with `;`, it become different thing. Think about this: `a, b = 1, 2` and `a; b = 1, 2`. The second will cause an error if `a` was not assigned before; and the value of `b` will be different. – falsetru Jan 03 '15 at 12:36
  • Sorry the ; was a typeerror, I meant a space between the underscore and the colon(,). _ , self._frame = .... Now its clear for me, thank you! – m harms Jan 03 '15 at 12:39
  • @mharms, Don't put a space before `,`: https://www.python.org/dev/peps/pep-0008/#id19 – falsetru Jan 03 '15 at 12:40
1

_ is just a variable like any other, however there are a few (contradictory) conventions for a variable called _. The one you see here is when you need to assign a result to a value that is not subsequently used: the retrieve method is returning two values and the programmer is only interested in the second one.

_ is also used in the interactive shell to store the result of the last expression.

_ is also used in some code as the name of a function that will translate a string, so _("some string") will lookup the string in a language specific table and return the appropriate translation or the original string if no translation is available.

Duncan
  • 92,073
  • 11
  • 122
  • 156