1

I was looking for a way to share a function across different classes to specific objects after their initialisation. I stumbled across some code, after some modification, that works exactly and efficiently for my app needs. The magic ingredient was to precede the function (initialised in a another function) with _,

I get the significance of the _ underscore operator and the , comma operator in some circumstances but I have never seen _, as an operator and can't find any info on searches. I really want to understand because it solved a major issue issue for me.

Some sample code (python/PyQt)

def setup_video(self):
    self.capture = cv2.VideoCapture("capture1.mp4")
    self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, self.video_size.width())
    self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, self.video_size.height())
    self.timer = QTimer()
    self.timer.timeout.connect(self.display_video_stream)
    self.timer.start(30)

def display_video_stream(self):
    """repaint QLabel widget.
    """
    _, frame = self.capture.read()
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    image = QImage(frame, frame.shape[1], frame.shape[0], 
                   frame.strides[0], QImage.Format_RGB888)
    self.image_label.setPixmap(QPixmap.fromImage(image))
cvw76
  • 99
  • 1
  • 9
  • 1
    It's throwing that part away. – Carcigenicate Dec 12 '17 at 13:43
  • 1
    @Carcigenicate only by convention – timgeb Dec 12 '17 at 13:45
  • 1
    @timgeb Yes. The intent is to show that you're throwing it away. – Carcigenicate Dec 12 '17 at 13:46
  • @Carcigenicate you marked as a duplicate. It isn't. I said specifically "\_,", whereas the link specifies "\_" in general. I understand that already, that is why I ask the specific question in relation to the specific code I posted. Otherwise, I can just read general python docs. It "could" be case 1 suggested in the link "To hold the result of the last executed expression" but I was hoping someone with applied knowledge (not theoretical) can say something like "ah, yes, you see in the 1st function you made this blah, blah, blah". A specific explanation made in relation to the posted code. – cvw76 Dec 12 '17 at 16:01
  • @cvw76 From the answer in the dupe: "3. As a general purpose "throwaway" variable name to indicate that part of a function result is being deliberately ignored, as in code like: label, has_label, _ = text.partition(':')". Unless I'm missing something, that exactly answers your question. – Carcigenicate Dec 12 '17 at 16:04
  • @cvw76 To clarify, `_,` is not an operator. It's just standard deconstruction of the collection `self.capture.read()` returns. An underscore is used as the first variable name to indicate that that data isn't needed. Your program would be exactly the same if you changed the underscore to a "normal" variable name. – Carcigenicate Dec 12 '17 at 16:23
  • Hi, that last point gets it for me. Thanks. – cvw76 Dec 14 '17 at 16:07

0 Answers0