Created
July 16, 2011 12:58
-
-
Save aliles/1086339 to your computer and use it in GitHub Desktop.
Syntactic sugar to replace '__name__' idiom with decorator
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 main import execute | |
@execute | |
def main(): | |
do_something() | |
def do_something(): | |
print "Hello World" |
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
"Convenience decorators for programs 'main'." | |
import atexit | |
import collections | |
def execute(func): | |
"""Register decorated function as main routine of program. | |
If the module is run as a script, the function will be registered to run | |
at exit: | |
>>> @execute | |
... def main(): | |
... print "Hello World" | |
The decorator can be made to register the function regardless of which | |
module is resides in: | |
>>> @execute(True) | |
... def main(): | |
... print "Hello World" | |
This decorator uses the atexit moodule so may not work correctly with code | |
that uses sys.exitfunc. | |
""" | |
if not isinstance(func, collections.Callable): | |
if func: | |
return atexit.register | |
return program | |
if func.__module__ == '__main__': | |
atexit.register(func) | |
return func |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment