0

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?

Han
  • 625
  • 2
  • 7
  • 25
  • This is probably more appropriate for code review if there are no bugs in the code you've provided. – Phantom Photon Nov 24 '17 at 16:03
  • @EdwardMoseley Okay, I will move it soon but I can't right now because I can only post once every 40 minutes. – Han Nov 24 '17 at 16:08
  • `argparse.Namespace` is a class that behaves much like your `AttrDict`. `parse_args` returns such an object, but you can create one yourself, `args=argparse.Namespace(foo='bar', verbose=True)`. – hpaulj Nov 24 '17 at 17:36

1 Answers1

1

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__

Clinton
  • 313
  • 1
  • 5
  • I think I was so obsessed with calling main method from impoting module. Thank you for your advice. – Han Nov 24 '17 at 17:39