KEMBAR78
Coercive __setattr__ support · Issue #6940 · python/mypy · GitHub
Skip to content

Coercive __setattr__ support #6940

@MasonMcGill

Description

@MasonMcGill

[Feature request / documentation enhancement proposal if it turns out this exists : ]

Hello, I'm looking for a way to support code like the following:

class Color:
    ''' [Many useful methods here] '''

class Palette:
    def __setattr__(self, key: str, value: object) -> None:
        ''' [Implicitly convert `value` to a `Color`.] '''

class SoftPastels(Palette):
    green: Color
    blue: Color

sp = SoftPastels()
sp.green = (127, 255, 127)  # -- "Incompatible types in assignment", MyPy 0.701
sp.blue = '#8888ff'         # -- "Incompatible types in assignment", MyPy 0.701

My use-case involves implicitly converting to numpy.ndarrays and/or h5py.Datasets, and I've seen this pattern (performing implicit conversion on attribute assignment) used to improve API ergonomics in a handful of other libraries (e.g. Pandas and the Blender API, IIRC).

Is there (or could there be) any way to type this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions