[Python-3000] callable()

Michael Chermside mcherm at mcherm.com
Wed Jul 26 22:43:29 CEST 2006


Andrew Koenig writes:
> I started the thread because I wanted to call attention to an issue: Objects
> sometimes have properties that have side effects when exploited, and it can
> be useful to be able to test for the presence of such properties without
> evoking the side effects.

Good point. I agree. I cannot list every possible property, but so far
three have been mentioned. For callability and iterability, I think that
hasattr(x, '__call__') and hasattr(x, '__iter__') are perfectly good
spellings for the test. You say:

> I felt uncomfortable about exposing the implementation that way

...but double-underscore methods are part of the language definition,
not part of the implementation. If we were saying to check whether
certain tp* fields in a C struct were populated, then I would object,
but checking for double-underscore methods doesn't expose
implementation. (It might, however, require the C implementation to
set some extra fields just to simulate having a __iter__ when it
really relies on tpIter. No big deal.)

Now, as Greg has pointed out, hashability cannot be tested in this
manner:

> since object has __hash__ we end up concluding that everything is
> hashable

Fortunately, I (and apparently others) believe this limitation is
OK because there is no need to test for hashability without evoking
the side effects. In general, __hash__ should be "quick" (which may
be a relative term) and return the same value each time it is
called, so simply calling __hash__ to find whether it works ought
to do nicely.

---

Much earlier, Andrew had also asked me this:

> Perhaps we are using "idempotent" to mean different things.  I think of a
> function f as being idempotent if f(x) == x for all x in dom(f).

Apparently so. In mathematics, the term means a function where
f(f(x)) = f(x) for all x. But in programming I have always understood
it to mean a function which will return the same result no matter how
many times it is invoked. In a quick glance at internet dictionaries
I found surprisingly little support for this definition, but I still
believe it is a fairly widely-used definition as I have heard it used
by co-workers from more than one job. The one source I DID find was
"http://en.wiktionary.org/wiki/idempotent".

-- Michael Chermside



More information about the Python-3000 mailing list