On Wed, Nov 12, 2014 at 2:33 PM, Chris Kaynor <ckay...@zindagigames.com> wrote: > A decorator is an interesting idea, and should be easy to implement (only > lightly tested): > > def main(func): > if func.__module__ == "__main__": > func() > return func # The return could be omitted to block the function from > being manually called after import. > > Just decorate the "main" function of the script with that, and it will be > automatically called when ran as a script, but not when imported as a > module.
This calls it at the wrong time, though. Typically the way this idiom is used is that you define everything you need (functions, classes, etc.) within the main script, and then you call the main function. This would call the main function at the time it's defined, when other things in the main script may not have been defined yet. One could place the main function last, but it would be preferable not to be forced. This also calls the function before it's been assigned to the global, which would prevent recursive calls of the main function. Instead of a decorator, I'd prefer to just have this: def main(func, *args, **kwargs): if func.__module__ == '__main__': func(*args, **kwargs) And then I can easily invoke it wherever I want in the main script. -- https://mail.python.org/mailman/listinfo/python-list