python getattr built-in method executes default arguments

后端 未结 1 420
旧时难觅i
旧时难觅i 2021-01-20 13:37

I dont know if this is something an expected behavior of getattr built_in method. getattr executes the default(3rd) argument as well even if the ac

相关标签:
1条回答
  • 2021-01-20 14:11

    Before getattr gets executed, all the passed parameters have to be evaluated. func() is one of those parameters and an attempt to evaluate it will execute the print statement. Whether the attribute will be found or not, func() must be evaluated apriori.

    This isn't peculiar to getattr, it's how functions and their parameters work in Python.


    Consider the following:

    >>> def does_nothing(any_arg): pass
    ...
    >>> def f(): print("I'll get printed")
    ...
    >>>
    >>> does_nothing(f())
    I'll get printed
    

    Function does_nothing actually does nothing with the passed parameter. But the parameter has to be evaluated before the function call can go through.


    The print statement however will not affect the outcome of getattr; sort of a side effect. In the event the attribute is not found the return value of the function is used.

    0 讨论(0)
提交回复
热议问题