Python: Import And Initialize Argparse After if __name__ == '__main__'?

PythonScripting

Python Problem Overview


If I am using argparse and an if __name__ == '__main__' test in a script that I would also like to use as a module, should I import argparse under that test and then initialize it? None of the style guides I have found mention using argparse in scripts and many examples of argparse scripting do not use the 'if name' test or use it differently. Here is what I have been going with so far:

#! /usr/bin/env python

def main(name):
    print('Hello, %s!' % name)

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description = 'Say hello')
    parser.add_argument('name', help='your name, enter it')
    args = parser.parse_args()

    main(args.name)

Should I import argparse with my other modules at the top and configure it in the body of the script instead?

Python Solutions


Solution 1 - Python

I would put the import at the top, but leave the code that uses it inside the if __name__ block:

import argparse

# other code. . .

def main(name):
    print('Hello, %s!' % name)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description = 'Say hello')
    parser.add_argument('name', help='your name, enter it')
    args = parser.parse_args()

    main(args.name)

Putting the imports at the top clarifies what modules your module uses. Importing argpase even when you don't use it will have negligible performance impact.

Solution 2 - Python

It's fine to put the import argparse within the if __name__ == '__main__' block if argparse is only referred to within that block. Obviously the code within that block won't run if your module is imported by another module, so that module would have to provide its own argument for main (possibly using its own instance of ArgumentParser).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanielView Question on Stackoverflow
Solution 1 - PythonBrenBarnView Answer on Stackoverflow
Solution 2 - Python101View Answer on Stackoverflow