[Python-ideas] Enhancing vars()
Nick Coghlan
ncoghlan at gmail.com
Tue Dec 13 06:28:03 EST 2016
On 13 December 2016 at 20:02, Steven D'Aprano <steve at pearwood.info> wrote:
> On Tue, Dec 13, 2016 at 10:29:38AM +0100, Marco Buttu wrote:
>
>> +1. Would it be possible in the future (Py4?) to change the name `vars`
>> to a more meaningful name? Maybe `namespace`, or something more appropriate.
>
> I'm not keen on the name vars() either, but it does make a certain
> sense: short for "variables", where "variable" here refers to attributes
> of an instance rather than local or global variables.
It also refers to local and global variables, as vars() is effectively
an alias for locals() if you don't pass an argument, and locals() is
effectively an alias for globals() at module level:
>>> locals() is globals()
True
>>> vars() is globals()
True
>>> def f(): return vars() is locals()
...
>>> f()
True
To be honest, rather than an enhanced vars(), I'd prefer to see a
couple more alternate dict constructors:
dict.fromattrs(obj, attributes)
dict.fromitems(obj, keys)
(With the lack of an underscore being due to the precedent set by
dict.fromkeys())
Armed with those, the "give me all the attributes from __dir__"
command would be:
attrs = dict.from_attrs(obj, dir(obj))
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list