134

In the function __getattr__(), if a referred variable is not found then it gives an error. How can I check to see if a variable or method exists as part of an object?

import string
import logging

class Dynamo:
 def __init__(self,x):
  print "In Init def"
  self.x=x
 def __repr__(self):
  print self.x
 def __str__(self):
  print self.x
 def __int__(self):
  print "In Init def"
 def __getattr__(self, key):
    print "In getattr"
    if key == 'color':
        return 'PapayaWhip'
    else:
        raise AttributeError


dyn = Dynamo('1')
print dyn.color
dyn.color = 'LemonChiffon'
print dyn.color
dyn.__int__()
dyn.mymethod() //How to check whether this exist or not

12 Answers 12

155

Check if class has such method?

hasattr(Dynamo, key) and callable(getattr(Dynamo, key))

You can use self.__class__ instead of Dynamo

Sign up to request clarification or add additional context in comments.

6 Comments

None is not callable, so you could just do callable(getattr(Dynamo, 'mymethod', None)). I used this answer because my super().mymethod() could throw AttributeError
@sbutler Interesting that that works. According to PyCharm the signature for getattr is def getattr(object, name, default=None): I suspect that is not accurate because if it was I would expect passing None as the third parameter not to change the behaviour of the function.
@bszom: In a python shell, help(getattr) says "When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case." -- (and indeed you can check that getattr does raise an exception if the attribute is missing) so clearly, whatever PyCharm is, it's wrong.
@ShreevatsaR Thanks for confirming my suspicion. PyCharm is an IDE.
SIMPLER VERSION: If you want to check if the current class INSTANCE has an attribute and it's callable, just do this: if hasattr(self, "work") and callable(self.work). This checks if the instance has a work attribute (can be either a variable or a function), and then checks if it's callable (meaning it's a function).
|
121

It's easier to ask forgiveness than to ask permission.

Don't check to see if a method exists. Don't waste a single line of code on "checking"

try:
    dyn.mymethod() # How to check whether this exists or not
    # Method exists and was used.  
except AttributeError:
    # Method does not exist; What now?

14 Comments

But perhaps he really doesn't want to call it, just to check if there is that method (as it is in my case)...
Note that this will fail if dyn.mymethod() raises an AttributeError itself.
as @DK says, this will trap any AttributeError that may be raised by the method being checked for, which may be undesirable (not to mention that it would wrongly infer the absence of the method in that case).
Good in principle, and Python does have an "exceptions as control flow" culture unlike other languages. However, if you are using exception logging tools such as Sentry/Raven, or New Relic, such exceptions have to be filtered out individually (if that's possible) or generate noise. I would prefer to check if the method exists rather than calling it.
This is wrong on so many levels. Method itself can raise AttributeError and this would be detected as method does not exist! It also ruins debugger support to break on exceptions. I'm also sure this probably impacts performance if thing was in loop. Last but not list I might not want to execute method, just validate if it exist. You should consider removing this answer or at least put all these warnings so naive folks don't get mislead.
|
113

How about dir() function before getattr()?

>>> "mymethod" in dir(dyn)
True

2 Comments

This does not check whether it is a method or a variable
using dir is not great - it doesn't confirm that the name is a method for instance
37

I use below utility function. It works on lambda, class methods as well as instance methods.

Utility Method

def has_method(o, name):
    return callable(getattr(o, name, None))

Example Usage

Let's define test class

class MyTest:
  b = 'hello'
  f = lambda x: x

  @classmethod
  def fs():
    pass
  def fi(self):
    pass

Now you can try,

>>> a = MyTest()                                                    
>>> has_method(a, 'b')                                         
False                                                          
>>> has_method(a, 'f')                                         
True                                                           
>>> has_method(a, 'fs')                                        
True                                                           
>>> has_method(a, 'fi')                                        
True                                                           
>>> has_method(a, 'not_exist')                                       
False                                                          

1 Comment

This answer is more suitable (in my opinion at least) than other answers because it does not use a general approach (using try statement) and it does check whenever the member is an actual function. great share!
19

You can try using 'inspect' module:

import inspect
def is_method(obj, name):
    return hasattr(obj, name) and inspect.ismethod(getattr(obj, name))

is_method(dyn, 'mymethod')

1 Comment

+1 for pointing to the inspect module. However, ismethod will fail with methods from parent classes. Your object might have the default __repr__ from object, but it is not a method of your class.
4

How about looking it up in dyn.__dict__?

try:
    method = dyn.__dict__['mymethod']
except KeyError:
    print "mymethod not in dyn"

3 Comments

underbar-prefixed methods by convention means 'private'.
double-underbar prefix plus double-underbar suffix means 'this is normally used by the Python interpreter itself' and usually there is some way to do achive the same effect from a user's program for the most common use cases (in this case it would be using dot notation for an attribute), but it is neither forbidden nor wrong to use it if your use case really calls for it.
It is not forbidden. The wrongness is subjective: it depends on how much you want to confuse programmers that adhere to conventions: don't use it unless you have no alternative.
4

Maybe like this, assuming all method is callable

app = App(root) # some object call app 
att = dir(app) #get attr of the object att  #['doc', 'init', 'module', 'button', 'hi_there', 'say_hi']

for i in att: 
    if callable(getattr(app, i)): 
        print 'callable:', i 
    else: 
        print 'not callable:', i

Comments

3

If your method is outside of a class and you don't want to run it and raise an exception if it doesn't exist:

'mymethod' in globals()

2 Comments

>>> def myadd(x,y): return x+y >>> 'myadd' in globals() True
If it is outside of a class, it is a function, not a method
1

For the people that likes simplicity.


class ClassName:
    def function_name(self):
        return

class_name = ClassName()
print(dir(class_name))
# ['__init__', .... ,'function_name']

answer = 'function_name' in dir(class_name)
print("is'function_name' in class ? >> {answer}")
# is 'function_name' in class ? >> True

1 Comment

Any downvote please let me know, So I can remove or edit the post!
0

I believe this approach also works and appears simpler to me.

class Dynamo:
    def __init__(self, x):
        pass
    def mymethod(self):
        pass

dyn = Dynamo('1')

if dyn.mymethod:
    print("mymethod is exist")
else:
    print("mymethod is not exist")

Just a note: it doesn't check whether it is callable or not, but it works if the method is unique and not duplicated with attributes or properties.

Comments

0

Here's a flexible solution:

def has_method_implementation(method: str, cls: type) -> bool:
    """
    Check if a method is implemented within a given class or its ancestors.

    Examples:
        Consider a class hierarchy where `BaseClass` defines a method `output` that raises
        `NotImplementedError`, and `SubClass` overrides `output` with its own implementation.

        ```python
        class Output:
            pass

        class BaseClass:
            def method(self, output: Any) -> Output:
                raise NotImplementedError()

        class SubClass(BaseClass):
            def method(self, output: Any) -> Output:
                # Implementation here
                return Output()

        # Check if `output` method is implemented in `BaseClass` and `SubClass`
        print(has_method_implementation('method', BaseClass))  # False
        print(has_method_implementation('method', SubClass))   # True

        # In your mother class, if the child has implemented the method.
        has_method_implementation('method', self.__class__) # True
        ```
    """
    # Get all the methods of the class
    for name, member in inspect.getmembers(cls, inspect.isfunction):
        if method == name and member.__qualname__.startswith(cls.__name__):
            return True
    else:
        return False

How to Use:

  • From within a class (e.g., mother class checking if child implements a method):

    # In your mother class, if the child has implemented the method.
    
    has_method_implementation('method_name', self.__class__)
    
  • Directly on a class:

    has_method_implementation('method_name', MyClass)
    

Replace 'method_name' with the actual method name you want to check.

This function checks if a method is implemented within a class (cls) by inspecting its methods.

Comments

-1

I think you should look at the inspect package. It allows you to 'wrap' some of the things. When you use the dir method it also list built in methods, inherited methods and all other attributes making collisions possible, e.g.:

class One(object):

    def f_one(self):
        return 'class one'

class Two(One):

    def f_two(self):
        return 'class two'

if __name__ == '__main__':
    print dir(Two)

The array you get from dir(Two) contains both f_one and f_two and a lot of built in stuff. With inspect you can do this:

class One(object):

    def f_one(self):
        return 'class one'

class Two(One):

    def f_two(self):
        return 'class two'

if __name__ == '__main__':
    import inspect

    def testForFunc(func_name):
        ## Only list attributes that are methods
        for name, _ in inspect.getmembers(Two, inspect.ismethod):
            if name == func_name:
                return True
        return False

    print testForFunc('f_two')

This examples still list both methods in the two classes but if you want to limit the inspection to only function in a specific class it requires a bit more work, but it is absolutely possible.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.