33

Is there a nicer way of doing the following:

try:
    a.method1()
except AttributeError:
    try:
        a.method2()
    except AttributeError:
        try:
            a.method3()
        except AttributeError:
            raise

It looks pretty nasty and I'd rather not do:

if hasattr(a, 'method1'):
    a.method1()
else if hasattr(a, 'method2'):
    a.method2()
else if hasattr(a, 'method3'):
    a.method3()
else:
    raise AttributeError

to maintain maximum efficiency.

7
  • Have you tested your theory that the second option is inefficient? It would surprise me if it wasn't more efficient than the first one. Mar 31, 2009 at 15:17
  • Oddthinking is likely correct. hasattr eliminates the need for an exception to be raised. Mar 31, 2009 at 15:34
  • 1
    Actually, the implementation of hasattr() essentially just calls getattr() and returns False if an exception is raised; see svn.python.org/view/python/tags/r254/Python/…
    – Miles
    Mar 31, 2009 at 16:02
  • That doesn't mean the second one wouldn't be faster, though. It depends on whether the first method is likely to exist.
    – Miles
    Mar 31, 2009 at 16:07
  • 13
    -1: Premature optimization. Why worry about performance? The first is clearly what you mean -- just do that and don't quibble about "efficiency" until you can prove that the exception is your bottleneck.
    – S.Lott
    Mar 31, 2009 at 16:47

6 Answers 6

27

A slight change to the second looks pretty nice and simple. I really doubt you'll notice any performance difference between the two, and this is a bit nicer than a nested try/excepts

def something(a):
    for methodname in ['method1', 'method2', 'method3']:
        try:
            m = getattr(a, methodname)
        except AttributeError:
            pass
        else:
            return m()
    raise AttributeError

The other very readable way is to do..

def something(a):
    try:
        return a.method1()
    except:
        pass

    try:
        return a.method2()
    except:
        pass

    try:
        return a.method3()
    except:
        pass

    raise AttributeError

While long, it's very obvious what the function is doing.. Performance really shouldn't be an issue (if a few try/except statements slow your script down noticeably, there is probably a bigger issue with the script structure)

1
  • 1
    I like the second one since it's very readable and straight-forward. If performance is really an issue, the original poster is probably doing something wrong. Apr 2, 2009 at 18:52
22

Perhaps you could try something like this:

def call_attrs(obj, attrs_list, *args):
    for attr in attrs_list:
        if hasattr(obj, attr):
            bound_method = getattr(obj, attr)
            return bound_method(*args)

    raise AttributeError

You would call it like this:

call_attrs(a, ['method1', 'method2', 'method3'])

This will try to call the methods in the order they are in in the list. If you wanted to pass any arguments, you could just pass them along after the list like so:

call_attrs(a, ['method1', 'method2', 'method3'], arg1, arg2)
6
method = (
        getattr(a, 'method1', None) or
        getattr(a, 'method2', None) or
        getattr(a, 'method3')
        )
method()

This will first look for method1, then method2, then method3. The search will stop as soon as one of them is found. If none of the methods are found the last getattr will raise an exception.

4

How about encapsulating the calls in a function?

def method_1_2_or_3():
    try:
        a.method1()
        return
    except AttributeError:
        pass
    try:
        a.method2()
        return
    except AttributeError:
        pass
    try:
        a.method3()
    except AttributeError:
        raise
1
  • 1
    Why the "encapsulating" part? just the pass is a nice enough idea, it seems to me.
    – cregox
    May 13, 2010 at 1:24
3

A compact solution:

getattr(a, 'method1',
    getattr(a, 'method2',
        getattr(a, 'method3')))()
1
  • 1
    Compact, but possibly wrong. If a has method1 but doesn't have method3, then this will fail. The third argument to getattr is evaluated before getattr is called, which means this code tries to fetch method3 before it ever considers method1 and method2. See Ethan Furman's answer for a safer alternative. May 14, 2014 at 15:49
1

If you are using new-style object:

methods = ('method1','method2','method3')
for method in methods:
    try:
        b = a.__getattribute__(method)
    except AttributeError:
        continue
    else:
        b()
        break
else:
    # re-raise the AttributeError if nothing has worked
    raise AttributeError

Of course, if you aren't using a new-style object, you may try __dict__ instead of __getattribute__.

EDIT: This code might prove to be a screaming mess. If __getattribute__ or __dict__ is not found, take a wild guess what kind of error is raised.

2
  • Definitely use the getattr() function instead of the getattribute method.
    – Miles
    Mar 31, 2009 at 16:00
  • I can't entirely figure out the relative advantages of getattr vs getattribute. There exist objects for which either will raise AttributeError and the other will work. Mar 31, 2009 at 21:38

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.