How about some syntactic sugar for " __name__ == '__main__' "?

Vito De Tullio vito.detullio at gmail.com
Sun Nov 16 05:39:34 EST 2014


Ian Kelly wrote:

>> 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.

for the "right time" you can choose to spin a thread and wait to the end of 
the load of the module

something like



from threading import Thread, current_thread

def run_func(func, module_thread):
    module_thread.join()
    func()

def main(func):
    if func.__module__ == '__main__':
        Thread(target=run_func, args=[func, current_thread()]).start()

    return func


-- 
By ZeD




More information about the Python-list mailing list