Python gives you a lot of power, like the ability to write code that will drive your static language programmer friends crazy...
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
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