Last active
August 29, 2015 14:02
-
-
Save rduplain/e637ac9205d7df82dff4 to your computer and use it in GitHub Desktop.
python: method delegation and copy-able threading.Lock
This file contains 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
from threading import Lock | |
def build_delegating_method(delegate_name, method_name): | |
def delegating_method(self, *a, **kw): | |
delegate = getattr(self, delegate_name) | |
method = getattr(delegate, method_name) | |
return method(*a, **kw) | |
doc_format = "Calls self.{}.{}." | |
delegating_method.__name__ = method_name | |
delegating_method.__doc__ = doc_format.format(delegate_name, method_name) | |
return delegating_method | |
def delegate_methods(cls): | |
for delegate_name in cls.delegated_methods: | |
for method_name in cls.delegated_methods[delegate_name]: | |
method = build_delegating_method(delegate_name, method_name) | |
setattr(cls, method_name, method) | |
return cls | |
@delegate_methods | |
class SimpleLock(object): | |
"threading.Lock duck type that is copy-able by copy std lib." | |
delegated_methods = { | |
'lock': [ | |
'acquire', | |
'release', | |
'__enter__', | |
'__exit__', | |
], | |
} | |
def __init__(self): | |
self.lock = Lock() | |
def do_copy(self): | |
return self.__class__() | |
def __copy__(self): | |
return self.do_copy() | |
def __deepcopy__(self, memo): | |
return self.do_copy() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment