Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hasattr on class names

Tags:

python

hasattr

hasattr documentation says that it takes an object and an attribute name and lets you know if that attribute exists on that object.

I have discovered that it seems to work on class names too (i.e. not an instance object).

Something like:

class A:
    def Attr1(self):
        pass

> hasattr(A, 'Attr1')
True
> 

I would like to use this to make some test code easier to write, but don't want to be bitten later in case this is a side effect of the implementation and not really intended.

Please don't ask to see the test code to see if I can do something else, as that is not really the question.

Is there any official python stance on this? I presume the object referred to, in the documentation is talking about an instance object.

I tried googling (and looking at some questions in StackOverflow), but didn't seem to find anything.

like image 870
Programmer Person Avatar asked Dec 20 '22 04:12

Programmer Person


1 Answers

The fact that it works on a class in addition to an instance is intentional. In fact, hasattr should work on any object that you pass to it. Basically, it does something like this:

def hasattr(obj, attribute):
    try:
        getattr(obj, attribute)
    except:
        return False
    return True

You can rely on that and not be afraid of getting bit by a change later. Note, there is some discussion on python-dev about hasattr being broken by design. The gist of it is that hasattr catches any exception which can be misleading.


Note that, in python classes are themselves instances of type.

>>> class Foo(object):
...   pass
... 
>>> type(Foo)
<type 'type'>

so everything is an instance of something1.

1type is an instance of itself which is something that would be impossible to do in pure python...

like image 187
mgilson Avatar answered Dec 21 '22 16:12

mgilson