-
-
Notifications
You must be signed in to change notification settings - Fork 33.9k
gh-143636: fix a crash when calling __replace__ on invalid SimpleNamespace instances
#143655
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
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.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I didn't want to change the existing behavior. Maybe we could decide in a follow-up PR how to change this?
| } | ||
| if (!_PyNamespace_Check(result)) { | ||
| PyErr_Format(PyExc_TypeError, | ||
| "%T.__new__() must return an instance of a subclass of %s", |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think about something like "%T() returned %T object". __new__() is rarely called directly.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I had this locally but I wondered whether this could be confused with __init__ or a simple function call.
SimpleNamespace.__replace__via re-entrant__new__#143636