Skip to content

Conversation

p-sawicki
Copy link
Collaborator

@p-sawicki p-sawicki commented Oct 3, 2025

The __setattr__ wrapper that mypyc generates needs to handle deleting attributes as well because del statements go through the same tp_setattro pointer but with the value argument set to NULL.

The wrapper calls __delattr__ in this case if it's overridden in the native class (or its parent). Handling of dynamic attributes is different without __dict__ which makes a custom __delattr__ required if the dynamic attributes are stored in a custom dictionary.

If __delattr__ is not overridden it calls the implementation of object.__delattr__ which results in AttributeError because there's no __dict__.

If it's defined without __setattr__, mypyc reports an error. It's possible to support just __delattr__ but since it shares a slot with __setattr__, the wrapper generation would be more complicated. It seems like an unlikely use case to only need __delattr__ so I think it makes sense to leave it for later.


# Doesn't work because there's no __delattr__.
with assertRaises(AttributeError):
del i.four
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe mypy could catch this? If four is not a declared attribute and there is no __delattr__, this is expected to fail. If you agree, can you create a mypy issue about this (unless one already exists)?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think mypy can catch this because this is a quirk of native classes. For interpreted classes that define __setattr__ deleting an attribute works without __delattr__ because it just removes it from __dict__. It's only native classes that might need an explicit __delattr__. So I think the error would be specific to mypyc.

@JukkaL JukkaL merged commit 374fefb into python:master Oct 6, 2025
13 checks passed
@p-sawicki p-sawicki deleted the dunder-setattr-handle-deletion branch October 6, 2025 15:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants