How about some syntactic sugar for " __name__ == '__main__' "?
ckaynor at zindagigames.com
Wed Nov 12 23:09:09 CET 2014
On Wed, Nov 12, 2014 at 1:51 PM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Wed, Nov 12, 2014 at 2:33 PM, Chris Kaynor <ckaynor at zindagigames.com>
> > 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
I was thinking along the lines of replacing:
if __name__ == "__main__":
<<<block of code>>>
<<<<block of code>>
Both blocks of code will be called at the same time.
> 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.
> On Wed, Nov 12, 2014 at 1:55 PM, Skip Montanaro <skip.montanaro at gmail.com>
> This won't work (I don't think) if you want to call the "main"
function from another place (like the interpreter prompt).
With the plain if block, you absolutely cannot call it elsewhere, without
wrapping it in a function anyways.
There is the issue, as mentioned by Ian, that the function will not be in
the module namespace at the time it is called. That does block it, however
it is also easy to work around: make the main function extremely simple,
such as just calling another function.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list