[Python-ideas] __vars__ special method

Yahya Abou 'Imran yahya-abou-imran at protonmail.com
Mon Jan 22 09:20:16 EST 2018


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.


Example for 1:


class C:

    __slots__ = 'eggs', 'spam'

    def __vars__(self):
        d = {}
        for attr in self.__slots__:
            if hasattr(self, attr):
                d[attr] = getattr(self, attr)
        return d


Exemple for 2:


class C:
    def __vars__(self):
        return {attr: value for attr, value in self.__dict__.items()
                if not attr.startswith('_')}



More information about the Python-ideas mailing list