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

Peter Otten __peter__ at web.de
Tue Dec 1 05:40:15 EST 2015


Manolo Martínez wrote:

> On 12/01/15 at 12:00pm, Steven D'Aprano wrote:
> > I'm trying to understand why vars() exists. Does anyone use it?
> 
> Well, I have this little podcast aggregator
> (https://github.com/manolomartinez/greg) that I and a bunch of other
> people use. I started writing it some years ago, and the code is a bit
> of a palimpsest, newer functionality reflecting my (somewhat) better
> understanding of the language. One of the oldest bits is this main()
> function:
> 
>         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)
>          
> 
> To judge by this thread, this is probably wrong/noobish?

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))

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





More information about the Python-list mailing list