I have a script that parses several arguments and has some expensive import data, but this import is only necessary if the user gives valid input arguments, otherwise the program will exit. In addition, when the user speaks python script.py --help
, there is no need for these expensive import operations to be performed at all.
I can think of a script like this:
import argparse
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--argument', type=str)
args = parser.parse_args()
return args
if __name__ == "__main__":
args = parse_args()
import gensim
import blahblahblah
def the_rest_of_the_code(args):
pass
if __name__ == "__main__":
the_rest_of_the_code(args)
It does the job, but it does not look elegant to me. Any best deals for this task?
EDIT : imports are really expensive:
$ time python -c "import gensim"
Using TensorFlow backend.
real 0m12.257s
user 0m10.756s
sys 0m0.348s
source
share