Skip to content

(🎁) Validate arguments to dataclasses utility functions replace and fields #14215

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

Closed
KotlinIsland opened this issue Nov 29, 2022 · 4 comments

Comments

@KotlinIsland
Copy link
Contributor

Mypy should special case these functions to only work with dataclasses.

from dataclasses import dataclass, replace

@dataclass
class D:
    pass
class C:
    pass

replace(D())
replace(C())  # TypeError: replace() should be called on dataclass instances

playground

PS: PyCharm correctly reports these

@jakezych
Copy link

Hello! I'm working with a team of CMU students and we're looking to contribute to this issue for a class project. I was wondering if anyone could give us some pointers on where to get started on this issue?

@A5rocks
Copy link
Collaborator

A5rocks commented Nov 29, 2022

I haven't touched the mypy code in a while but there's a dataclass plugin in the source which would be the first place I would look. Barely knowing anything my instinct is either to make dataclass generated classes inherit from some pretend class if there isn't already some marker (there probably is lol), and then... I don't know, patch mypy's typeshed? Maybe override replace calls? I'd look at the plugin API to see if that's even possible.

But please take everything I said with a grain of salt!


Better researched response:

There's plugins in mypy's source, see mypy/plugins. Update the "default" one's get_function_hook to add the error. To detect if a class is a dataclass, simply check type.metadata (I think?) which probably has something useful. It does for attrs at least!

@AlexWaygood
Copy link
Member

Looks like there's a lot of interest in fixing this! We've already had two PRs filed over at mypy and one over at typeshed, so I think we probably don't need any more PRs for this one -- let's concentrate on reviewing what we've already got 😀

@AlexWaygood
Copy link
Member

Fixed in python/typeshed#9362

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment