Double underscores -- ugly?

Duncan Booth duncan.booth at invalid.invalid
Tue Feb 19 10:01:18 CET 2008


Berwyn <berhoyt at gmail.com> wrote:

>> Is it just me that thinks "__init__" is rather ugly? Not to mention
>> "if __name__ == '__main__': ..."?
> 
> That ugliness has long been my biggest bugbear with python, too.  The
> __name__ == '__main__' thing is something I always have to look up,
> every time I use it, too ... awkward.
> 
> I'd settle for:
> 
>     hidden def init(self):          # which could be extended to work
> for everything "hidden x=3"
>     ...
> 
> And for __name__ == '__main__' how about:
> 
>     if sys.main():
>         ...

Or even:

  @hidden
  def init(self): ...

@main
def mymainfunc():
   ...


The first of those probably wants some metaclass support to make it work 
cleanly, but here's a sample implementation for the second one:

import sys, atexit
def main(f):
    """Decorator for main function"""
    def runner():
        sys.exit(f())
    if f.func_globals['__name__']=='__main__':
        atexit.register(runner)
    return f

print "define mymainfunc"
@main
def mymainfunc(args=sys.argv):
    print "Got args", args
    return 3
print "end of script"

If you have multiple functions marked as main that will run them in 
reverse order, so it might be better to put them on a list and use a 
single runner to clear the list. Also, I have no idea what happens to 
the exit code if you use this decorator more than once.

BTW, should anyone be wondering, you can still use atexit inside a 
function called from atexit and any registered functions are then called 
when the first one returns.



More information about the Python-list mailing list