Pythonic style

Chris Angelico rosuav at gmail.com
Wed Apr 27 23:56:05 EDT 2016


On Thu, Apr 28, 2016 at 1:52 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
>
> The point Ben was trying to make is this:  you should never* call __dunder__
> methods in normal code; there is no need to do so:
>
> - use len(), not __len__()
> - use next(), not __next__()
> - use some_instance.an_attribute, not some_instance.__dict__['an_attribute']
>
> --
> ~Ethan~
>
> * Okay, maybe /almost/ never.  About the only time you need to is when
> giving your classes special methods, such as __add__ or __repr__.

My rule of thumb is: Dunders are for defining, not for calling. It's
not a hard-and-fast rule, but it'll get you through 99%+ of
situations.

ChrisA



More information about the Python-list mailing list