[Python-ideas] __vars__ special method

Steven D'Aprano steve at pearwood.info
Mon Jan 22 12:41:45 EST 2018


On Mon, Jan 22, 2018 at 09:20:16AM -0500, Yahya Abou 'Imran via Python-ideas wrote:
> On top of this old proposition:
> https://bugs.python.org/issue13290
> 
> We could have a __vars__ method that would be called by vars() if defined.
> The use cases:
> 
> 1. let vars() work with instances without __dict__;
> 2. hide some attributes from the public API.

I think you may have misunderstood the purpose of vars(). It isn't to be 
a slightly different version of dir(), instead vars() should return the 
object's namespace. Not a copy of the namespace, but the actual 
namespace used by the object.

This is how vars() currently works:

py> class X:
...     pass
...
py> obj = X()
py> ns = vars(obj)
py> ns['spam'] = 999
py> obj.spam
999


If vars() can return a modified copy of the namespace, that will break 
this functionality.



-- 
Steve


More information about the Python-ideas mailing list