Skip to content

Instantly share code, notes, and snippets.

@durden
Created December 14, 2012 14:47
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save durden/4285944 to your computer and use it in GitHub Desktop.
Python gives you a lot of power, like the ability to write code that will drive your static language programmer friends crazy...
def call_only_once(func):
def new_func(*args, **kwargs):
if not new_func._called:
try:
return func(*args, **kwargs)
finally:
new_func._called = True
else:
# We already called the real func once, so let's pick a completely
# different one from the globals and call it instead
import random
import inspect
funcs = [ob for ob in globals().values() if inspect.isfunction(ob)]
# Remove this func b/c it takes args and we don't want to
# re-decorate this method or anything weird...er :)
funcs.remove(call_only_once)
funcs.remove(new_func)
fake_func = random.choice(funcs)
# The downfall of this is could be a mismatch in arguments between
# the decorated function and the random one we choose. Not sure of
# a good way to avoid this, but this is not code you should ever
# use anyway :)
return fake_func(*args, **kwargs)
new_func._called = False
return new_func
def x():
return 'called x'
def y():
return 'called y'
@call_only_once
def z():
return 'called z'
if __name__ == "__main__":
print 'Calling z().................', z()
print 'Calling z() again........ :)', z()
print 'Calling z() again........ :)', z()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment