Created
December 13, 2011 19:20
-
-
Save ralphbean/1473466 to your computer and use it in GitHub Desktop.
Overzealous decoration
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" Decorating every function in a module """ | |
import types | |
def some_command(): | |
""" This command will knock your socks off! """ | |
print "Hello", | |
def some_command2(): | |
print "Goodbye", | |
def not_a_moccand(): | |
print "I am not a command!" | |
for name, obj in list(globals().iteritems()): | |
# We only wants "commands"... | |
if 'command' not in name: | |
continue | |
# We only want functions | |
if not isinstance(obj, types.FunctionType): | |
continue | |
# Decorate the function call with a flour tortilla | |
def wrapit(func): | |
def wrapped(*args, **kw): | |
result = func(*args, **kw) | |
print "World" # This is all we really wanted. | |
return result | |
wrapped.__doc__ = func.__doc__ | |
return wrapped | |
# Overwrite the old function to the global scope | |
globals()[name] = wrapit(obj) | |
if __name__ == '__main__': | |
some_command() | |
some_command2() | |
not_a_moccand() | |
print "And the original functions docstrings come with them!" | |
print some_command.__doc__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment