Han
Han

Reputation: 735

What is the best practice for parsing arguments in Python?

As I don't have much experience in Python, I'm always trying to follow the Google Python Style Guide. The guide contains the following sentence.

"Even a file meant to be used as a script should be importable and a mere import should not have the side effect of executing the script's main functionality."

Therefore, I searched for a way to override __getattr__, and have been using this ArrtDict class for arguments parsing as follows.

import argparse

class AttrDict(dict):
    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)
        self.__dict__ = self

def parse_args(args):
    if isinstance(args, list):
        parser = argparse.ArgumentParser()
        parser.add_argument('--args1')
        return parser.parse_args(args)
    else:
        return AttrDict(args)

def main(args):
    args = parse_args(args)

if __name__ == '__main__':
    import sys
    main(sys.argv[1:])

What would be the best practice for arguments parsing in Python?

Upvotes: 0

Views: 2537

Answers (1)

Clinton
Clinton

Reputation: 323

What the sentence you're referring to is saying is that you should have this line in your script file:

if __name__ == '__main__':

And that any code that runs the script should appear in that block. By doing so, you ensure that the code won't automatically run when you import it from another file, since importing ignores the if statement mentioned above.

For processing arguments (which should exist in the if block mentioned above, since you wouldn't want to do that when importing), you should use argparse for everything after Python 2.7. Here's a link to the documentation:

Python argparse library

You shouldn't have to override __getattr__

Upvotes: 1

Related Questions