On Tue, Dec 29, 2020 at 8:11 AM Steven D'Aprano email@example.com wrote:
On Mon, Dec 28, 2020 at 11:36:55PM -0800, Christopher Barker wrote:
Side Question: when should one use __dict__ vs vars() vs getattr() ???
three work in this case, but I'm never quite sure which is prefered, and why.
`vars(obj)` is defined as returning `obj.__dict__` so technically it probably doesn't matter, but I feel that as a matter of aesthetics and future-proofing, we should avoid direct use of dunders whenever practical.
To the contrary, vars() is something I added to the language for the benefit of REPL users (like dir()), and other usages look suspect to me. I find that using `__dict__` is more direct about the purpose, and also it is the prevailing style.
Do you prefer to write `mylist.__len__()` over `len(mylist)`? Then you will probably prefer `obj.__dict__` over `vars(obj)` too :-)
Not a valid analogy.