Theresa O’Connor

A syntax for Python’s hasattr

It used to be that, if you had a dict foo and you wanted to see if it had the key bar, you’d write foo.has_key(bar). At some point,1 people decided extending the in operator to handle this case would be more pythonic, so we now write bar in foo. This isn’t limited to built-in types — it (usually) works by passing bar to foo’s __contains__ method.

As I’ve become more accustomed to using the in operator in such cases, hasattr has started to bother me. In fact, hasattr(foo, 'bar') feels quite un-pythonic to me now. Perhaps a has operator2 could restore balance to the Force; how do you think this looks?

foo has 'bar'

This could work behind the scenes via a __hasattr__ method, much like the existing __getattr__, __setattr__, and __delattr__ methods.

The odds are really good that something like this has already come up, however, cursory Google searching didn’t reveal anything.

Now, I know what you’re thinking. “Ted,” you ask, “do we really need additional __foo__s? Don’t you think Python already has way too many of these things?” And, to be fair, I concede some of that, at least the bit about __ being ugly.

But syntax aside, I think these things are great and I want more of them. I’m really fond of these Python constructs which allow programmes to override default behavior in a controlled way — they’re Python’s manifestation of what Christophe calls protocol-oriented programming. There’s a reason why I love AMOP so much. When you get right down to it, Python is an acceptable lisp.

Notes

  1. Judging by the docs, I’m pretty sure this happened between 2.1 and 2.2.
  2. I suppose we could make a concession to all the lolcode fans out there:

    i can has 'cheezburger'

    No, no, maybe not.