
A Guide to Python's Magic Methods - cskau
http://www.rafekettler.com/magicmethods.html
======
mitchellh
This is a great post, but I also want to point out that this page is
invaluable to any Python developer wanting to know the details about the magic
methods: [http://docs.python.org/reference/datamodel.html#special-
meth...](http://docs.python.org/reference/datamodel.html#special-method-names)

Whenever working on any reasonably complex class, I find that open in a tab to
verify that I'm using the magic methods properly, and that they'll be called
as I expect.

~~~
rafekett
I agree. What I wrote here was based on that.

I wanted my post to be more akin to a tutorial than a reference. I don't think
the data model reference is useful to people who don't know the basics -- the
idea was to bridge that gap so that it could be useful.

------
steve-howard
>__getattr__(self, name)

> ... This can be useful for catching and redirecting common misspellings ...

I can think of only one _good_ reason to redirect spelling errors, and that's
if you are a widely-used library and you want to support both "color" and
"colour" (and similar Britishisms). Other than that, you're just asking for a
headache.

~~~
jules
It would be perhaps be useful to throw an error saying "X object has no
attribute Y, did you mean Z instead?".

~~~
steve-howard
That's probably a better idea. In either case being "liberal in what you
accept" is a discredited software practice.

~~~
mhansen
_being "liberal in what you accept" is a discredited software practice._

What? When did that get discredited?

~~~
steve-howard
Not entirely discredited; I spoke too strongly. It's not a good idea to be
more liberal than the situation calls for; here's a discussion on the subject:

[http://programmers.stackexchange.com/questions/12401/be-
libe...](http://programmers.stackexchange.com/questions/12401/be-liberal-in-
what-you-accept-or-not)

------
MikeOnFire
For each special method, you should show what syntax magically invokes it.
Something like this:

foo.__iter__() is invoked by for x in foo a.__iadd__(b) is invoked by a += b
a.__rmult__(b) is invoked by b * a when b * a fails. foo.__len__() is invoked
by if foo when foo.__bool__ or foo.__nonzero__ is not defined. foo.__repr__()
is invoked by '%r' % foo, also by pprint.pprint(foo) and deprecated `foo`.
It's also invoked by __str__ magic when foo.__str__ is not defined. etc.
Putting the above info in a table would also be helpful.

~~~
rafekett
This was my work (not sure why someone randomly posted it here, but such is
the internet).

I do exactly what you just described, see
<http://www.rafekettler.com/magicmethods.html#appendix>

~~~
cskau
Such is the Internet indeed.

I stumbled upon this while researching some Python magic. I felt it was a
pretty good write-up so I decided to share it with my fellow HN'ers.

Thank you for posting this.

~~~
rafekett
And thank you for posting. I'll take all of the traffic I can get :)

------
zanny
This might be tangental, but the syntax of having magic methods be surrounded
by double underscores always drives me insane. For a language designed around
readability, it seems like the python dev team just kicked the can on things
like __init_ and said "Sure, we have a few dozen english words already
restricted usage in the language, but let's kick the whole "pretty" thing out
and start wrapping every special statement in ugly underscores like its 1995
again!".

They probably started this trend around 1995, now that I think about it, ya
know. since the language is that old and all.

It is still really annoying, I just cringe when I use __init__ constructors
because they look so ugly in otherwise very English-document-like source.

</rant>

~~~
njharman
Special methods are special. It is a feature that they look different and
stand out.

~~~
batista
Well, they could stand out with some better say.

How about a "special" keyboard?

def special init()

How about @?

def @init()

or ::

def special::init()

or, all caps, like Go does initial-cap for exported members:

def INIT()

~~~
lclarkmichalek
Well @ is taken by decorator syntax. I like the python way however (probably
due to using python a lot). Special methods are special so it does make sense
that they look different, and python all ready the convention that underscores
in front of them function name indicate the function shouldn't be accessed
directly, and that is true for special methods. When was the last time you
called __init__ directly (discounting uses inside another __init__ method)?
Most likely never. I guess it's personal preference, but that naming
convention saves me a lot of time when calling die on an object; I know I can
basically ignore anything after the first name beginning with an underscore.

------
njharman
Controlling Attribute Access section is really poor. Giving poor explanation
of getattr vs getattribute, wrongly recommending to not use these methods,
claiming there is little use, and providing poor examples of common use cases.
The biggest of which is object composition.

~~~
jeffjose
I'm not sure who downvoted you, but I felt the same.

Its been a while since I've been through getattr vs getattribute pages, but I
distinctly remember there's a big big difference in how you use them. I was
kinda hoping the page had it, but unfortunately it didnt.

Original Author, if you're reading this - kindly do that.

~~~
SoftwareMaven
__getattribute__ (new classes only!) hijacks the entire lookup machinery;
every time you write _instance._ , you will call it.

__getattr__ allows "normal" lookup (is it a method, does it exist in __dict__,
etc) to be done by the VM and isn't called until you would otherwise get an
AttributeError.

------
sophacles
One of the better treatments of __get__ and __set__ I've seen. Descriptors are
deep and powerful magic, and a bit complex, but when they are appropriate,
they are less complex than the alternatives, and allow for cleaner interfaces.

