I have a simple and possible dumb question.
getattr(obj, 'attribute', 2+2)
Question is - would default 2 + 2
be evaluated only in case 'attribute' is missing or it would be evaluated in any case?
Thanks
I have a simple and possible dumb question.
getattr(obj, 'attribute', 2+2)
Question is - would default 2 + 2
be evaluated only in case 'attribute' is missing or it would be evaluated in any case?
Thanks
You can test this yourself by creating an object with an add function that lets you know it was called. For example, you can see the function prints "called" in bother cases indicating that the addition is evaluated regardless of whether the attribute exists on the object:
class obj:
a = "value from obj"
class N:
def __add__(self, other):
print('called')
return 5
a = N()
b = N()
getattr(obj, 'a', a + b)
# called
#'value from obj'
getattr(obj, 'z', a + b)
# called
# 5