Search code examples
pythonargs

Importing class imports argparse options as well


I have a script x_1.py, in which I defined a class Class_X.

Another script I am using is x_2.py, in which I have the following line:

from x_1 import Class_X

Both scripts x_1.py and x_2.py have different argsparse options. When I call python x_1.py --h, I get the correct argument options for x_1.py. When I call python x_2.py --h, I receive the argument options of x_1.py, instead of those for x_2.

Any idea how to fix this...?


Solution

  • Most likely (unless you are doing something really odd), you want to add a guard to x_1.py to protect code that isn't meant to be run if the script is imported instead.

    def some_function():
       pass
    
    p = argparse.ArgumentParser()
    p.add_argument(...)
    
    if __name__ == "__main__":
        args = p.parse_args()
        # do some other stuff
    

    Now, if you import x_1 into another module, only some_function and p will be defined; p.parse_args will not be called, and p itself will only be used if x_2 decides to use it. If p is of no interest to other modules, its definition and configuration can be moved into the if statement as well.