Main function decorator (for Python 2 and 3).
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
|locale = inspect.stack().f_locals|
|module = locale.get("__name__", None)|
|if module == "__main__":|
|locale[function.__name__] = function|
Jul 24, 2020
Is this still working with Python 3.8? I tried to get it running but it seemed to have no effect.
Sep 12, 2020
I haven't used it for years to be honest. I tested it before posting it, but that was ages ago.
Jul 26, 2022
The following modifications work fine for me under 3.10.5
from inspect import stack def automain( func ) : locale = stack()[ 1 ].frame.f_locals module = locale.get( '__name__', None ) if module == '__main__' : locale[ func.__name__ ] = func func() return func
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Any functions decorated by
mainare automatically invoked if they are in a top-level script, else the decorator does nothing.
The idea was taken from automain by Gerald Kaszuba. It's been tweaked to allow the decorated function to be called recursively and repeatedly.
First, import the decorator:
If this code is in the top level script, the function will be invoked automatically:
The decorator works with recursive functions:
You can call decorated functions normally: