New submission from Martin Thurau:

If you have a descriptor (in my case it was an SQLAlchemy column) on an 
instance and this descriptor returns None for a call to __get__ then getattr 
with a given default value, will not return the default, but None.

I have no knowledge on the implementation details of getattr but I guess the 
logic is something like this:
- getattr looks at the given object and sees that the attribute in question is 
not None (since it is the descriptor object)
- getattr returns the descriptor
- the descriptors __get__ method is called
- __get__ return None

Maybe it should be more like this:
- getattr looks at the given object and sees that the attribute in question is 
not None (since it is the descriptor object)
- getattr sees that the attribute has __get__
- getattr calls __get__ method and looks if the return value is None

I'm not sure if this is really a bug but it's highly confusing and somewhat 
un-pythonic. I really should not care of an attribute of an object is a value 
or a descriptor. This is especially true since this problem also applies to 
@property. Effectively this means that if you call getattr you have *know* if 
the name in question is a property or not and one can't simply swap out an 
objects value for a property without risking to break calling code.

If this is actually *not* a bug, we should at least update the documentation to 
getattr, to mention this fact. Because currently it states that "getattr(x, 
'foobar') is equivalent to x.foobar" which is obviously not true.

----------
components: Interpreter Core
files: python_descriptor_bug.py
messages: 212876
nosy: Martin.Thurau
priority: normal
severity: normal
status: open
title: getattr does not work well with descriptor
type: behavior
versions: Python 2.7
Added file: http://bugs.python.org/file34299/python_descriptor_bug.py

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue20864>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to