Python offers any number of ways to create very Pythonic interfaces to your objects, natural ways of getting various bits of information out of them. For an example that is fresh to my mind , the
len()
of M2Crypto 's
Cipher
objects is the number of bits that the cipher uses.
The M2Crypto example also illustrates the problem with this way of creating interfaces: it is not necessarily very intuitive to people using your code. The
len()
of a cipher being its bits strikes me as Pythonic (and it certainly is the closest to the 'length' of a cipher object), but it is not obvious. Short of reading documentation (or in this case, reading the source), there is nothing that points to len(Cipher-object) being the way to get this particular piece of information out of Cipher objects.
So I would like to suggest that you consider the merits of giving your objects obvious interfaces too. Adding a
.bits()
method may not be as elegant as
len()
, but it has the virtue that it is more likely to be noticed by people in the output of
dir()
and other introspection tools.
(I don't know about other people, but I use introspection in the interactive interpreter a lot when I am trying to figure out how to bang together some code. I also tend to skip entirely over the
__X__
entries when reading
dir()
's output, partly because all objects have a certain amount of noise there.)
Having said this, I will admit that in retrospect I have committed my share of clever, Pythonic, and not all that obvious interfaces in my own code. I'll have to remember this the next time I am tempted to add a
__len__
method to something.
(I don't think that docstrings are entirely the answer. Again, perhaps it's just me but I'm more likely to look first at
dir()
's output and only second at docstrings. And of course,
dir()
is always there while docstrings need someone to write them, which doesn't always happen.)