Skip to content

Instantly share code, notes, and snippets.

@n1k0
Created June 28, 2012 15:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save n1k0/3012006 to your computer and use it in GitHub Desktop.
Save n1k0/3012006 to your computer and use it in GitHub Desktop.
Attribute fallback in Python - useful when you cannot extend an existing class, or want a proxy
class Bar(object):
def plop(self):
print 'plop'
class Foo(object):
def __init__(self):
self.bar = Bar()
def do(self):
print 'done'
def __getattribute__(self, attr):
try:
return object.__getattribute__(self, attr)
except AttributeError as initial:
try:
return object.__getattribute__(self.bar, attr)
except AttributeError:
raise initial
>>> Foo().do()
done
>>> Foo().plop()
plop
>>> Foo().unexistent
AttributeError: 'Foo' object has no attribute 'unexistent'
@brunobord
Copy link

maybe use hasattr(), instead of the try... except?

http://docs.python.org/library/functions.html#hasattr

@brunobord
Copy link

... and/or gettattr?

@n1k0
Copy link
Author

n1k0 commented Jun 28, 2012

You can't use them because they use __getattribute__ themselves… you'd be ending with recursion errors :)

@brunobord
Copy link

ah. never mind, then

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment