Skip to content

Instantly share code, notes, and snippets.

@lukauskas
Last active August 29, 2015 14:21
Show Gist options
  • Save lukauskas/6f34e001941d3d686ccf to your computer and use it in GitHub Desktop.
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)
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