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

Steven D'Aprano steve at pearwood.info
Tue Dec 1 20:12:56 EST 2015


On Tue, 1 Dec 2015 07:44 pm, 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?

I've seen worse :-)

Checking the error message in that way is risky. As an absolute last resort,
I guess it works, but it's hack-ish (not in a good way) and fragile. The
problem is, error messages are not part of the Python API and are subject
to change without warning.

(Aside: when I design my language, I'm going to ensure that error messages
vary from one exception to the next, specifically to discourage this :-)

Today, you get an error message 

"'Namespace' object has no attribute 'func'"

(note that there is no need to escape the single quotes) but there's no
guarantee that this will always be the same. Tomorrow it could silently
change to:

'"Namespace" instance does not have a "func" attribute.'

and your code will break. Better and safer is:


def main():  # parse the args and call whatever function was selected
    args = parser.parse_args(sys.argv[1:])
    try:
        func = args.func
    except AttributeError as err:
        parser.print_help()
    else:
        func(vars(args))



-- 
Steven




More information about the Python-list mailing list