Is vars() the most useless Python built-in ever?

Manolo Martínez manolo at austrohungaro.com
Tue Dec 1 16:31:00 EST 2015


Peter, thanks for taking the time to look into my code.

On 12/01/15 at 11:40am, Peter Otten wrote:
> Manolo Martínez wrote:
> >         def main():  # parse the args and call whatever function was 
> selected
> >                 try:
> >                         args = parser.parse_args(sys.argv[1:])
> >                         args.func(vars(args))
> >                 except AttributeError as err:
> >                         if str(err) == "\'Namespace\' object has no 
> attribute \'func\'":
> >                                 parser.print_help()
> >                         else:
> >                                 print("Something has gone wrong: 
> {}".format(err), file = sys.stderr, flush = True)
> 
> What probably is typical for a beginner in that snippet is that you don't 
> trust the exception system and handle exceptions that will never occur once 
> the script is debugged. Just write
> 
> args = parser.parse_args()
> args.func(vars(args))

Well, one fully possible situation is for the user to mistype a
subcommand. In that case, the script outputs the help provided by
argparse, so that they know what is and isn't meaningful. That is what
the "if str(err)..." is doing.

The else clause is there to output the traceback (in full trust of the
exception system ;) in case the error was not due to the user mistyping.

Is there a better way to do this?

> Now vars(). I see nothing wrong with it, but when I look into one of your 
> func implementations
> 
> > def info(args):  # Provides information of a number of feeds
> >     session = Session(args)
> >     if "all" in args["names"]:
> >         feeds = session.list_feeds()
> >     else:
> >         feeds = args["names"]
> >     for feed in feeds:
> >         pretty_print(session, feed)
> 
> I come to the conclusion that passing args directly could make your life 
> easier:
> 
> def info(args):  
>     """Provides information of a number of feeds"""
>     session = Session(args)
>     if "all" in args.names:
>         feeds = session.list_feeds()
>     else:
>         feeds = args.names
>     for feed in feeds:
>         pretty_print(session, feed)
> 
> As far as I can see there is only one place where the key is not a constant, 
> and you can rewrite that from 
> 
> >         try:
> >             if args[value]:
> >                 return args[value]
> >         except KeyError:
> >             pass
> 
> to
> 
> try:
>     answer = getattr(args, value)
>     if answer: 
>         return answer
> except AttributeError:
>     pass
> 

This is very helpful, thanks a lot! 

Manolo



More information about the Python-list mailing list