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

Ethan Furman ethan at stoneleaf.us
Thu Nov 13 21:43:15 CET 2014


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 11/13/2014 12:33 PM, Ian Kelly wrote:
> On Thu, Nov 13, 2014 at 11:32 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
>> On 11/12/2014 01:51 PM, Ian Kelly wrote:
>>> 
>>> On Wed, Nov 12, 2014 at 2:33 PM, Chris Kaynor 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.
>>> 
>>> This calls it at the wrong time, though.  [...]
>> 
>> One decorator that won't call too early is atexit.register().
> 
> Nice. That feels like an abuse, though. The actual program won't be able to register its own atexit handlers,
> because the program will already be exiting, and other things decorated with atexit.register might actually be
> called before the main function.

It's definitely a niche use-case -- such as a cli-helper lib:  import said lib, and when it's decorators are used set
the atexit handler to call the lib's __main__ function, which checks that the module name of the decorated function is
'__main__', and if it is, run stuff!

Hmmm... hopefully that wasn't difficult to explain.  ;)

- --
~Ethan~
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)

iQIcBAEBAgAGBQJUZRfjAAoJENZ7D1rrH75Nx4IP/3tuR4JhVK6Acv04+DiHm32H
BHGmBRZGtXQrHGEBcv8BlvUiztmrHqjV+Lkm78zKF3n9R8Ta9qTeSjqIsjRWUMtR
JVraCSH6usUwmcGITXIYKQHdXynl+ylu9p8Hr3NT2aNoICqowVGSvK3Ie1NmJuf3
lJcl8tXiXgUrGCwBwEgdrBKTdaATe4QT9XFQJx1QbXpF3qT1Za5hPYthY3fH/Pd9
Nl9NHyA6F5x4sSO7itD23UtUpnRBHWl7blwsKkBi7ClfacxJMrYjFAMUaxUaiTFF
/bygveskmMAZw87ISLtjkmOcKtsi0i2BQSQEjpBDZTiveCD/wyDDhJ+5pmZKzll0
Q+pISt4jG9hkArd+JCCxPuTCCo2xm+cMIB4/oSeONd760u6vURLPUNZ5tmNsRkiZ
o0/EwyRhWPZotiLoyi7kDNyfpj/BSKV0A6Ph+M40UXOkTZFUf0E84OFEpB359MTO
rIvHDpd6Tzch2Dliuj6UKZ1OOygIZauv2ebmEBHHNDMdsVbhdtTElS1Rh2JtDVyZ
tUd67KTmE9CwOPcFIbYKHXGIf4FWDAgeaz9x8RY4UUPaDRlyG1eqSxx8Vob2AG9c
MEawmA48JCj52ZeICQf6nnIFdIowFkV7QssUgte3cVfbcMBYnPx/nuJWWMjULo77
WrIUpisDf/juvXn4VtuO
=oczI
-----END PGP SIGNATURE-----



More information about the Python-list mailing list