[Tutor] argparse iterable

Don Jennings dfjennings at gmail.com
Tue Apr 2 03:56:16 CEST 2013


On Apr 1, 2013, at 8:31 PM, <kendy at kendy.org> <kendy at kendy.org> wrote:

> <snip>
> 
> print("But this doesn't iter through a b and c:")
> for k,v in parser.parse_args():
>    print('This arg is %s %s' % k, k[str(v)])
> $ 
> -------------------------------------------------------------------------
> 
> My error:
> $ h.py -a -b hi -c 42
> Namespace(a=True, b='hi', c=42)
> But this doesn't iter through a b and c:
> Traceback (most recent call last):
>  File "./h.py", line 16, in <module>
>    for k,v in parser.parse_args():
> TypeError: 'Namespace' object is not iterable
> $ 
> 
> How can I get parser to be iterable?

Jason, Mark and Dave have addressed this part of your question already.

> 
> After I get it to iter, I suppose that I'll be bitten by the boolean and integer
> type conversions. I'm not sure how to handle that either. Will 'str()' save me?

What do you mean here? You're thinking that you have to convert them to strings before passing them to the print function? Actually, the string formatting operator, the percent sign, combined with the 's' will convert for you, using the str() method. So, the code above is redundant. Just use:

print('This arg is %s %s' % k, v)

Take care,
Don



More information about the Tutor mailing list