Created
April 29, 2017 05:55
-
-
Save dboyliao/5d6c2995109fdb410a1528cdd8f7da87 to your computer and use it in GitHub Desktop.
Mimic Swift extension syntax in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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