Welcome, guest | Sign In | My Account | Store | Cart

Use this decorator to remove the UGLY "if __name__ == '__main__':"

Python, 16 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
'''
entrypoint.py
2011 JUL 14
@author: Yoav Glazner 
'''

def entry_point(f):
    '''
    example:
        @entry_point
        def main():
            print("hello world")
    '''
    if f.__module__ == '__main__':
        f()
    return f

4 comments

Yaşar Arabacı 12 years, 8 months ago  # | flag

It seems more like more trouble then putting if __name__ == "__main__" to me.

Stephen Chappell 12 years, 8 months ago  # | flag

Will this work properly when the main function is at the top of file instead of at the bottom after all the classes and functions have been defined?

Ethan Furman 12 years, 7 months ago  # | flag

No, it needs to be at the bottom, just like normal.

Clever bit of code.

Oren Tirosh 12 years, 3 months ago  # | flag

Pass command line args to function, return exitcode to OS:

def entry_point(f):
    if f.__module__ == '__main__':
        import sys
        sys.exit(f(*sys.argv[1:]))
    return f
Created by yoav glazner on Thu, 14 Jul 2011 (PSF)
Python recipes (4591)
yoav glazner's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks