The operating system (or shell) first parses the command line, passing the lines to the Python interpreter, where they are available to you as an sys.argv array.
python palindrome.py 'Taco cat!?'
becomes
['palindrome.py', 'Taco cat!?']
parser.parse_args() processes these lines, usually just passing the links around. When the base argument is βparsedβ, this string is βstoredβ in the namespace with setattr(Namespace, dest, value) , which in your example would be equivalent to setattr(namespace, 'string', sys.argv[1]) .
There is nothing special about argparse.Namespace . This is a simple subclass of Object . Arguments are simple attributes of an object. argparse uses setattr and getattr to access them, although users can usually use the dot format ( args.string ). It does not perform special string processing. This is entirely Python's responsibility.
The namespace is not iterable, that is, it is not a list or tuple, or something like that. This is an object. The namespace can be converted to a dictionary with vars(args) (this is in the argparse documentation). This way you can iterate over this dictionary with keys and items .
One more thing. Do not test arg.string with is . Use == or in [] to compare it with other lines. This is because the line created with sys.argv does not have the same id as the one created with x = 'test' . To understand why, try:
argv = 'one two three'.split() print argv[0]=='one' # true print argv[0] is 'one' # false print argv[0] in ['one', 'two','three'] # true x = 'one' print x is 'one' # true print id(x) print id('one') print id(argv[0])
Whenever possible, Python stores unique copies of strings. but if the strings are generated differently, they will have different identifiers and do not satisfy the is test.
hpaulj
source share