Skip to content
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

Prevent @dataclass from being called twice on the same class #92231

Open
ericvsmith opened this issue May 3, 2022 · 6 comments
Open

Prevent @dataclass from being called twice on the same class #92231

ericvsmith opened this issue May 3, 2022 · 6 comments
Assignees
Labels
3.11 bug and security fixes stdlib Python modules in the Lib dir type-feature A feature request or enhancement

Comments

@ericvsmith
Copy link
Member

Currently it's possible to do this:

@dataclass(repr=False)
@dataclass(repr=True)
class C:
    pass

This is confusing at best, and will produce unexpected classes at worst.

With this change, that will become an error.

@ericvsmith ericvsmith added the type-feature A feature request or enhancement label May 3, 2022
@ericvsmith ericvsmith self-assigned this May 3, 2022
@ericvsmith ericvsmith added stdlib Python modules in the Lib dir 3.11 bug and security fixes labels May 3, 2022
@ericvsmith
Copy link
Member Author

See #92052

@rohitsanj
Copy link

I thought about how we could implement this for a bit -- and it looks like we would need to add an extra class attribute that would act as a flag, say __dataclass_decorator_called__, and then check whether it's been set or not in the wrap inner function. If it has been set, we raise a TypeError.

I guess the only caveat is if the class definition already contains an attribute with the same name as the flag, in which case, this implementation would erroneously raise an exception even if the @dataclass decorator was used just once.

@MojoVampire
Copy link
Contributor

@rohitsanj: All names that begin and end with __ (e.g. the proposed flag you give) are reserved for use by Python and subject to breakage with no warning. We're allowed to blithely destroy any and all code using __*__ names in any way that does not conform to the existing set of special methods, so using such a flag is not a problem in that sense.

@rohitsanj
Copy link

Thanks for the clarification, @MojoVampire

@ericvsmith
Copy link
Member Author

I already have this coded up, using __dataclass_fields__ as the indicator. I'm holding off on it until the discussion in #92052 is resolved.

@ericvsmith
Copy link
Member Author

See PR #92518.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
3.11 bug and security fixes stdlib Python modules in the Lib dir type-feature A feature request or enhancement
Projects
None yet
Development

No branches or pull requests

3 participants