Python: Import And Initialize Argparse After if __name__ == '__main__'?
Solution 1:
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:
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 it's own argument for main
(possibly using it's own instance of ArgumentParser
).