Skip to content

Instantly share code, notes, and snippets.

@n1k0
Created June 28, 2012 15:30
Show Gist options
  • 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'
@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