Skip to content

(馃巵) Validate arguments to dataclasses utility functions replace and fields聽#14215

Description

@KotlinIsland

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

Activity

  1. jakezych commented on Nov 29, 2022

    @jakezych

    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?

  2. A5rocks commented on Nov 29, 2022

    @A5rocks
    Collaborator

    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!

  3. AlexWaygood commented on Dec 14, 2022

    @AlexWaygood
    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 馃榾

  4. AlexWaygood commented on Jan 28, 2023

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions