2

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

Aleksei Khatkevich
  • 1,923
  • 2
  • 10
  • 27
  • 5
    It would have to be evaluated regardless, as `getattr` is, afaik, just a simple function without any magic behind it. As a function, its arguments must be evaluated first before it's called. – Carcigenicate Jul 17 '20 at 15:02
  • 1
    Python uses eager evaluation – function arguments are always evaluated before being passed to the function. Note that you can test this easily, e.g. via ``print(getattr(obj, 'attribute', print("default")))`` – MisterMiyagi Jul 17 '20 at 15:02

1 Answers1

2

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
Mark
  • 90,562
  • 7
  • 108
  • 148