[Python-ideas] Specificity in AttributeError

Ethan Furman ethan at stoneleaf.us
Sat Apr 27 07:49:09 CEST 2013


On 04/26/2013 09:44 PM, Devin Jeanpierre wrote:
> Code:
>       class A:
>          @property
>          def text(self):
>              return self.foo
>
> Behavior:
>      >>> hasattr(A(), 'text')
>      False
>
> Actually, this is absolutely correct. "A().y" does not give a result
> -- in fact, it raises AttributeError. Behavior wise, this is exactly
> what it means for an attribute to not exist.

I think you "A().foo" and not "A().y" above.


> The problem is that this may disguise other issues in one's code.

Like bugs?  ;)


> I would like to be able to write this function:
>
> def hasattr_lite(obj, attr):
>      try:
>          getattr(obj, attr)
>      except AttributeError as e:
>          if e.object is obj and e.attribute is attr:
>              return False
>          raise
>      return True
>
> Does that sound reasonable?

While it's always nice to have extra info in exceptions, why are you coding against bugs?

If this is your own code you should have unit tests to catch such things.

If this is someone else's code... well, it's their bug.

--
~Ethan~



More information about the Python-ideas mailing list