Dunder variables

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Jan 9 03:34:59 EST 2018


On Tue, 09 Jan 2018 09:55:49 +0200, Frank Millman wrote:

> Hi all
> 
> I have read that one should not call dunder methods in application code.

"Should not" rather than "must not", but that's correct. In general, 
calling a dunder method directly is *not* the same as the operation you 
probably want. For example, `x + y` may not be the same as `x.__add__(y)` 
or `y.__radd__(x)`. Better to use `operator.add(x, y)` instead.


> Does the same apply to dunder variables? I am thinking of the instance
> attribute __dict__, which allows access to the contents of the instance.
> 
> I only want to read from __dict__, not update it. Is this frowned upon?

If you are trying to look up obj.attribute where you don't know the name 
of the attribute until runtime, the right way is to use getattr:

    name = 'spam'  # this is unknown until runtime
    value = getattr(obj, name)  # like obj.spam


If you want to avoid inheritance and avoid looking up attributes on the 
class or any superclasses, but only look it up on the instance, then the 
nice way is to use vars(obj):

    vars(obj)['attribute']


But be aware that not all objects even have a __dict__ -- not even all 
those with data attributes.



-- 
Steve




More information about the Python-list mailing list