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

Rick Johnson rantingrickjohnson at gmail.com
Tue Dec 1 00:54:09 EST 2015


On Monday, November 30, 2015 at 7:01:14 PM UTC-6, Steven D'Aprano wrote:
> I'm trying to understand why vars() exists. Does anyone use it?

I think your "mental dilemma" stems from the fact that python was originally created to be an easy language for noobs to learn (which it still mostly is), however, over the years, feature creep has expanded this small general purpose language to include many specific applications. The "vars" function is a relic of the early days of Python and has not evolved because 99% of Python hackers find it to be useless. I mean, heck, print did not evolve until Py3! Outside of a few test sessions in my early days with Python, I don't remember ever using the vars function again. 

Your lament does remind me of a pet peeve i have concerning Python, and that is, the lie about: "THERE SHOULD BE ONE (AND PREFERABLY ONLY ONE) WAY TO DO IT!". In fact, in python there is almost always *MANY* ways to achieve the same output. 

For instance, consider the output of vars(), globals(), locals(), dir(), and obj.__dict__. In many cases, all of these, or at least most of these, will return the same answer(s). Not only is that type of interface repetitive, it superfluously obfuscates the underling paths by which the value is obtained. 

We may find this difficult to believe, but many a noob has been stumped by the following questions:

(1) How do you output a message without the print function?

(2) How do you fetch a listing of an object's methods without the dir function?

Listen, there is nothing wrong with creating "layers of abstraction". In fact, without abstractions, we could not evolve our technologies, however, if these "layers" are not intentionally crafted in logical order, then we quickly move away from the intuitive structure of a "cake model" and into the dreaded nightmare of the "spaghetti model". We should strive to structure our code in the image of a MandelBot set (think: "levels of detail"), not a hedge maze labyrinth of an "Overlook Hotel"!



More information about the Python-list mailing list