dunder-docs (was Python is DOOMED! Again!)

Ethan Furman ethan at stoneleaf.us
Sun Feb 1 03:12:10 EST 2015


On 01/31/2015 09:36 PM, Rustom Mody wrote:
> 
> And a student asked me the diff between
> dir([])
> and
> [].__dir__()
> 
> I didnt know what to say...
> Now surely the amount of python I dont know is significantly larger than what I know
> Still it would be nice to have surface-syntax ←→ dunder-magic more
> systematically documented

I don't have a complete answer for you, but I can say this:

In simple cases (such as __len__) there is little difference between calling the surface operator and the dunder version
(the error message differs in this case).

In more complex cases (such as __add__) using the surface syntax (+) buys lots of extras:

  - if one operand is a subclass of the other, calling its __add__ or __radd__ method as appropriate
  - if the first operand returns NotImplemented, calling the other operand's __radd__ to see if that works
  - possibly others that I don't recall at the moment

Basically, unless you're programming at the system (or class internals) level, don't call dunder methods directly.

--
~Ethan~

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20150201/9e32e3a6/attachment.sig>


More information about the Python-list mailing list