gh-143636: fix a crash when calling __replace__ on invalid SimpleNamespace instances#143655
Conversation
…`SimpleNamespace` instances
| if (!result) { | ||
| return NULL; | ||
| } | ||
| if (!_PyNamespace_Check(result)) { |
There was a problem hiding this comment.
There are many ways to clone an object, you should make a decision whether call __init__ and/or __new__bor just create an instance of the base class. This is done differently for other types.
The following code follows the way of __reduce__() (which is also used in copy.copy()). It is equivalent to:
new_ns = type(ns)()
new_dict = dict(ns.__dict__)
for k, v in kwargs.items():
new_dict[k] = v
for k, v in new_dict.items():
new_ns.__dict__[k] = vbut more efficient.
This is what copy.copy() will execute.
We can implement this for the case when the result of type(ns)() is not a SimpleNamespace, but this will add an amount of code, and all this for the case which perhaps never occurs in real code. So, I am fine with simply raising an error.
There was a problem hiding this comment.
I didn't want to change the existing behavior. Maybe we could decide in a follow-up PR how to change this?
|
@serhiy-storchaka Do you want me to address your concerns or are you fine with the current approach I took? I didn't want to change the way we construct the instances so that I can backport this fix and I suggest that we address the construction alternatives in a follow-up PR. WDYT? |
vstinner
left a comment
There was a problem hiding this comment.
LGTM. Adding _PyNamespace_Check() test sounds like the right fix for this problem. I don't have a strong opinion on the error message.
|
Thanks @picnixz for the PR 🌮🎉.. I'm working now to backport this PR to: 3.13, 3.14. |
…`SimpleNamespace` instances (pythonGH-143655) (cherry picked from commit 9796856) Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
|
Sorry, @picnixz, I could not cleanly backport this to |
|
GH-145938 is a backport of this pull request to the 3.14 branch. |
|
GH-145940 is a backport of this pull request to the 3.13 branch. |
SimpleNamespace.__replace__via re-entrant__new__#143636