[Tutor] Argparse and how best to use it
Dave Angel
davea at davea.name
Thu Oct 24 18:50:34 CEST 2013
On 24/10/2013 11:38, Paradox wrote:
> I am trying to learn about argparse and how best to incorporate it into
> my scripts. I am using Python 2.7.5 on Ubuntu 13.10.
Welcome to python, and to python-tutor mailing list. And thanks for
using text mode email, and for supplying both your Python version and
OS.
>
> It seems from the argparse tutorial that all the arguments are processed
> as global variables. Is that the standard way to do it or do you
> normally (when doing real projects and not writing tutorials) process
> the arguments in the main loop of the script?
Not sure which tutorial you're using, but the refernce page:
http://docs.python.org/3.3/library/argparse.html
has some examples that are also at top-level, using globals. I wouldn't
recommend that, as I try to minimize the number of non-const globals.
The only component that might make sense as a global is the result
dictionary, 'args'
So the first example would become:
import argparse
def parse_my_args():
global args
parser = argparse.ArgumentParser(description='Process some
integers.')
parser.add_argument('integers', metavar='N', type=int,
nargs='+', help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate',
action='store_const', const=sum, default=max, help='sum the integers
(default: find the max)')
args = parser.parse_args()
Technically, I should just return args, but this is the way I do it for
my own code. Although args is technically non-const, by making it a
global, I am promising myself that nobody else will modify it once set
up.
--
DaveA
More information about the Tutor
mailing list