How about some syntactic sugar for " __name__ == '__main__' "?
Vito De Tullio
vito.detullio at gmail.com
Sun Nov 16 11:39:34 CET 2014
Ian Kelly wrote:
>> def main(func):
>> if func.__module__ == "__main__":
>> 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
> 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
for the "right time" you can choose to spin a thread and wait to the end of
the load of the module
from threading import Thread, current_thread
def run_func(func, module_thread):
if func.__module__ == '__main__':
Thread(target=run_func, args=[func, current_thread()]).start()
More information about the Python-list