#๐Ÿ”’ dunder method questions

33 messages ยท Page 1 of 1 (latest)

timber tartanBOT
#

@azure ibex

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

peak zodiac
#

Think about Number(5) + Number(5) + Number(5) actually become
Number(5).__add__(Number(5)).__add__(Number(5))

#

So when you compute Number(5).__add__(Number(5)) and get the equivalent of Number(10), it essentially becomes Number(10).__add__(Number(5)

#

Basically syntax sugar kind of thing

#
  1. Eventually it go to level of C++ code which handled it
abstract timber
#

There's no "triggering another one" in the int class

peak zodiac
#

In this case, int

#

int is written in C++, not python

abstract timber
#

Which in turn uses a binary algorithm to add ints

abstract timber
#

CPython, not CppPython hah

#

the official Python interpreter is written in C

#

all the builtin types are written in C

#

it's a python object still, just at the C level

craggy marlin
#

why would the __add__ in int cause Number.__add__ to be triggered?

#

damn, I didn't see the history

#

anyways, instead of TypeError you should just return NotImplemented

#

this lets the other operand implement its own __add__

abstract timber
peak zodiac
#

Even if it works without reversing

abstract timber
#

!e

class A:
    def __add__(self, other):
        print("add first")

class B:
    def __radd__(self, other):
        print("radd first")

A() + B()
timber tartanBOT
peak zodiac
#

Hmm

abstract timber
#

it goes like this

  1. try to call __dunder__ on the LHS
  2. if that fails, try to call __rdunder__ on the RHS
#

!e therefore, this errors

class A: ...

class B:
    def __add__(self, other):
        print("add")

A() + B()
timber tartanBOT
peak zodiac
#

Hmm ok

abstract timber
#

part of the reason is that you can't assume the operator is commutative for the given operands

#

for example, string concatenation is not commutative

timber tartanBOT
#
Python help channel closed using Discord native close action

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.