Skip to content

Instantly share code, notes, and snippets.

@aliles
Created July 16, 2011 12:58
Show Gist options
  • Save aliles/1086339 to your computer and use it in GitHub Desktop.
Save aliles/1086339 to your computer and use it in GitHub Desktop.
Syntactic sugar to replace '__name__' idiom with decorator
from main import execute
@execute
def main():
do_something()
def do_something():
print "Hello World"
"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