On 2021-06-23 10:21 a.m., Steven D'Aprano wrote:
What about other functions implemented in C? If I write a C module that calls PyObject_GetAttr, does it behave as if dot notation were used in the module that called me, or does it use my module's extension methods?
That depends. If you write a C module that calls PyObject_GetAttr right now, is that *exactly* the same as dot notation in pure-Python code?
The documentation is terse:
but if it is correct that it is precisely equivalent to dot syntax, then the same rules will apply. Has the current module opted in? If so, then does the class have an extension method of the requested name?
Same applies to code objects evaluated without a function, or whatever other exotic corner cases you think of. Whatever you think of, the answer will always be the same:
if the execution context is a module that has opted to use extension methods, then attribute access will see extension methods;
if not, then it won't.
If you think of a scenario where you are executing code where there is no module scope at all, and all global lookups fail, then "no module" cannot opt in to use extension methods and so the code won't see them.
If you can think of a scenario where you are executing code where there are multiple module scopes that fight for supremacy using their two weapons of fear, surprise and a fanatical devotion to the Pope, then the winner will determine the result.
But if getattr is part of the builtins module, written in C, and the builtins module is calling PyObject_GetAttr, and PyObject_GetAttr is exactly the same as the dot notation...
Then getattr is exactly the same as the dot notation, **in the builtins module**! The builtins module doesn't use any extension methods, as it is written in C. As such getattr(foo, "bar") MUST NOT produce the same result as foo.bar if extension methods are at play!
(You're still missing the point of extension methods. Do check out our other reply.)