Skip to content

Instantly share code, notes, and snippets.

@stephanh42
Created February 10, 2017 19:00
Show Gist options
  • Save stephanh42/97b47506e5e416f97f5790c070be7878 to your computer and use it in GitHub Desktop.
Save stephanh42/97b47506e5e416f97f5790c070be7878 to your computer and use it in GitHub Desktop.
Python class extensions a la Objective-C "categories"
#class extensions a la Objective-C "categories"
#using metaclasses
excluded_methods = frozenset(["__module__", "__qualname__"])
def class_extend(cls):
class Meta(type):
def __new__(self, name, bases, attrs, **kwargs):
for name, value in attrs.items():
if name not in excluded_methods:
setattr(cls, name, value)
return cls
return Meta
# example of class extension follows
# define a base class
class FooBase(object):
def foo(self):
return 42
# override method
class Foo(FooBase):
def foo(self):
return 43
# make an instance
foo = Foo()
# let's extend Foo. Note that super() will start lookup in FooBase
class Foo(metaclass=class_extend(Foo)):
def foo(self):
return super().foo()
# yes we get 42
print(foo.foo())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment