On Thu, Mar 31, 2016 at 11:08 PM, Justin C. Walker <jus...@mac.com> wrote: > Hi, all, > > I have couple of questions regarding "attributes" in Python/Sage: > > 1. If hasattr(X, "foo") returns True, does that mean that "X.foo" should not > blow up?
Yes, this does, because unfortunately hasattr(X, 'foo') actually access the .foo attribute, which is a pain when dealing with properties and other descriptors that may take some time to execute. The inverse, however, is very different, and different between Python 2 and Python 3. On Python 3 any exception in the attribute lookup will result in hasattr(obj, 'foo') returning False. For example: $ python2 Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class A: ... @property ... def foo(self): ... return 1/0 ... >>> hasattr(A(), 'foo') False The point here is that *any* exception from an attribute lookup results in hasattr False. On Python 3 they "fixed" that (in my opinion). Only an AttributeError raised from the attribute lookup results in hasattr False--any other exception bubbles up: $ python3 Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> class A: ... @property ... def foo(self): ... return 1 / 0 ... >>> hasattr(A(), 'foo') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 4, in foo ZeroDivisionError: division by zero >>> class B: ... @property ... def foo(self): ... raise AttributeError('foo') ... >>> hasattr(B(), 'foo') False (Unfortunately this is still not perfect--an AttributeError for an unrelated attribute raised by a subroutine when accessing 'foo' can still result in hasattr('foo') == False :( One of my top wishlist items for Python 4 is some kind of __hasattr__ special method for classes and/or an equivalent for descriptors that merely guarantees* that accessing the attribute of that name will not result in an AttributeError. That would be extremely useful for checking attribute availability without computing / returning a value. I've never found a good workaround for that otherwise. Erik * This is of course an interface guarantee made by the programmer--it is still subject to bugs. > 2. Is there a way to tell, when hasattr(X, "foo") returns True, whether > "X.foo" can be called? > > 3. If "X.foo" is callable, is it expected that "X.foo()" will *not* blow up > with "Not Implemented"? > > I'm hoping that makes sense... -- You received this message because you are subscribed to the Google Groups "sage-devel" group. To unsubscribe from this group and stop receiving emails from it, send an email to sage-devel+unsubscr...@googlegroups.com. To post to this group, send email to sage-devel@googlegroups.com. Visit this group at https://groups.google.com/group/sage-devel. For more options, visit https://groups.google.com/d/optout.