Skip to content

Instantly share code, notes, and snippets.

@dboyliao
Created April 29, 2017 05:55
Show Gist options
  • Save dboyliao/5d6c2995109fdb410a1528cdd8f7da87 to your computer and use it in GitHub Desktop.
Save dboyliao/5d6c2995109fdb410a1528cdd8f7da87 to your computer and use it in GitHub Desktop.
Mimic Swift extension syntax in Python
# -*- coding: utf-8 -*-
from __future__ import print_function
from functools import wraps
def extension(cls, verbose=False):
if not isinstance(cls, type):
raise ValueError("{} is not a class".format(cls))
def func_deco(func):
if verbose and func.__name__ in globals():
print("Warning, overwriting {} in global scope".format(func.__name__))
@wraps(func)
def wrapped(*args, **kwargs):
return func(*args, **kwargs)
setattr(cls, func.__name__, wrapped)
return func_deco
class MyClass(object):
def __init__(self, name):
self.name = name
@extension(MyClass)
def say(self, msg):
print("{} says {}".format(self.name, msg))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment