71

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?

Chuck
  • 4,662
  • 2
  • 33
  • 55
Daniel
  • 745
  • 1
  • 6
  • 6

2 Answers2

77

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.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • 12
    [PEP 8](https://www.python.org/dev/peps/pep-0008/#imports) does recommend importing all modules at the top of the file. I would assume there's no exception for scripts using the entry point test. – Daniel Jan 15 '15 at 05:59
7

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).

jtlz2
  • 7,700
  • 9
  • 64
  • 114
101
  • 8,514
  • 6
  • 43
  • 69
  • That makes sense. That 'if name' test would prevent any unnecessary modules from being imported(probably saving some system resources). As long as it doesn't offend any style conventions to import modules at the bottom, that's what I will go with. – Daniel Jan 15 '15 at 05:41
  • 1
    Personally I agree with BrenBarn that it's a _bit_ nicer to have them all at the top, but it would work either way. More discussion [here](http://stackoverflow.com/questions/128478/should-python-import-statements-always-be-at-the-top-of-a-module). – 101 Jan 15 '15 at 05:50