Skip to content

Instantly share code, notes, and snippets.

@carlsmith carlsmith/automain.py
Last active Jan 19, 2017

Embed
What would you like to do?
Main function decorator (for Python 2 and 3).
import inspect
def main(function):
locale = inspect.stack()[1][0].f_locals
module = locale.get("__name__", None)
if module == "__main__":
locale[function.__name__] = function
function()
return function
@carlsmith

This comment has been minimized.

Copy link
Owner Author

carlsmith commented Feb 13, 2015

Features

Any functions decorated by main are automatically invoked if they are in a top-level script, else the decorator does nothing.

  • You can decorate more than one function.
  • More than one decorated function can be in the same file.
  • You can call the decorated function recursively.
  • Decorated functions can also be called like normal functions.

The idea was taken from automain by Gerald Kaszuba. It's been tweaked to allow the decorated function to be called recursively and repeatedly.

Use

First, import the decorator:

from automain import main

If this code is in the top level script, the function will be invoked automatically:

@main
def f(): print("hello world")

The decorator works with recursive functions:

@main
def f(n=3):
    print(n)
    if n: f(n - 1)

You can call decorated functions normally:

f(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.