Last active
August 29, 2015 14:21
-
-
Save lukauskas/6f34e001941d3d686ccf to your computer and use it in GitHub Desktop.
Python functions locked without setup() function (see https://twitter.com/randal_olson/status/599610510795874304)
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 __future__ import print_function | |
from functools import wraps | |
class UnitialisedFunctionCallException(Exception): | |
pass | |
def setup_function(function_): | |
@wraps(function_) | |
def setter(self, *args, **kwargs): | |
try: | |
ans = function_(self, *args, **kwargs) | |
except: | |
pass | |
else: | |
self.__initialised__ = True | |
return ans | |
return setter | |
def needs_setup(function_): | |
@wraps(function_) | |
def setter(self, *args, **kwargs): | |
try: | |
initialised = self.__initialised__ | |
except AttributeError: | |
initialised = False | |
if not initialised: | |
raise UnitialisedFunctionCallException( | |
'Function {!r} called without appropriate initialisation' \ | |
.format(function_)) | |
return function_(self, *args, **kwargs) | |
return setter | |
class A(object): | |
@setup_function | |
def setup(self, some_arg): | |
self.some_arg = some_arg | |
@needs_setup | |
def print_some_arg(self, parameter): | |
print(self.some_arg, parameter) | |
# >>> a = A() | |
# >>> a.print_some_arg('test') | |
# UnitialisedFunctionCallException: Function <function print_some_arg at 0x10d0ca5f0> called without appropriate initialisation | |
# >>> a.setup('derp') | |
# >>> a.print_some_arg('test') | |
# derp test |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment