Handling argparse conflicts
Question: If I import a Python [module](https://github.com/paulcalabro/api-
kickstart/blob/master/examples/python/config.py) that is already using
**argparse** , however, I would like to use **argparse** in my script as well
...how should I go about doing this?

I'm receiving a _unrecognized arguments_ error when using the following code
and invoking the script with a -t flag:

**Snippet:**

    
    
    #!/usr/bin/env python
    
    ....
    import conflicting_module
    import argparse
    ...
    
    #################################
    # Step 0: Configure settings... #
    #################################
    parser = argparse.ArgumentParser(description='Process command line options.')
    parser.add_argument('--test', '-t')
    

**Error:**

    
    
     unrecognized arguments: -t foobar
    


Answer: You need to guard your **imported modules** with

    
    
    if __name__ == '__main__':
        ...
    

against it running initialization code such as argument parsing on import. See
[What does `if __name__ == "__main__":`
do?](http://stackoverflow.com/questions/419163/what-does-if-name-main-do).

So, in your `conflicting_module` do

    
    
    if __name__ == '__main__':
        parser = argparse.ArgumentParser(description='Process command line options in conflicting_module.py.')
        parser.add_argument('--conflicting', '-c')
        ...
    

instead of just creating the parser globally.

If the parsing in `conflicting_module` is a mandatory part of application
configuration, consider using

    
    
    args, rest = parser.parse_known_args()
    

in your main module and passing `rest` to `conflicting_module`, where you'd
pass either `None` or `rest` to `parse_args`:

    
    
    args = parser.parse_args(rest)
    

That is still a bit bad style and actually the classes and functions in
`conflicting_module` would ideally receive parsed configuration arguments from
your main module, which would be responsible for parsing them.

