On Mon, Aug 23, 2010 at 17:04, Benjamin Peterson <benja...@python.org> wrote: > 2010/8/23 Steven D'Aprano <st...@pearwood.info>: >> On Tue, 24 Aug 2010 06:50:19 am Guido van Rossum wrote: >> >>> > * Is there anything that hasattr(obj, key) can or should do that >>> > can't already be done with getattr(obj, key, None)? >>> > If not, do we really need to change anything? >>> >>> getattr(obj, 'key', None) returns None when obj.key exists and has >>> the value None. The workaround is ugly. >> >> Why do you say it's ugly? It's a short, sweet, simple two-liner: >> >> mark = object() >> getattr(obj, 'key', mark) is not mark >> >> Nothing ugly about it at all. But if somebody really objected to using a >> two lines, they could put it in a utility function. > > That's not all, though. You still have to test it with an "if" and > that gets cumbersome after a while.
It is also non-obvious to any beginner. Are we really going to want to propagate the knowledge of this trick as a fundamental idiom? I would rather leave hasattr in that instance. But I'm +1 on only swallowing AttributeError. -Brett > >> >> I have always thought that hasattr() does what it says on the box: it >> tests for the *existence* of an attribute, that is, one that statically >> exists rather than being dynamically generated. In other words, it is a >> key in the instance __dict__ or is inherited from the class __dict__ or >> that of a superclass, or a __slot__. >> >> Now that I know that hasattr doesn't do what I thought it does or what >> the name implies it does, it has little or no utility for me. In the >> future, I'll just write a try...except block and catch errors if the >> attribute doesn't exist. > > Well, that's exactly what hasattr does... > > > > -- > Regards, > Benjamin > _______________________________________________ > Python-Dev mailing list > Python-Dev@python.org > http://mail.python.org/mailman/listinfo/python-dev > Unsubscribe: > http://mail.python.org/mailman/options/python-dev/brett%40python.org > _______________________________________________ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com