Thanks to visit codestin.com
Credit goes to github.com

Skip to content

TypedMapping for extended compatibility? #1952

Open
@ego-thales

Description

@ego-thales

Hello,

Consider the following, where lock aims at making provided argument immutable.

@dataclass
class Works:
    foo: Mapping

    def lock(self) -> None:
        self.foo = MappingProxyType(self.foo)

It works great with mypy, no issue. Now imagine I want to enforce a bit more to foo by requesting it be compatible with a Movie. I would try the following, without success.

class Movie(TypedDict):
    author: str
    year: int

@dataclass
class Fails:
    foo: Movie

    def lock(self) -> None:
        self.foo = MappingProxyType(self.foo)  # error: Incompatible types in assignment (expression has type "MappingProxyType[str, object]", variable has type "Movie")  [assignment]

Is there an workaround? If not, is if a good idea to discuss the possibility of a TypedMapping, that would simply work as follow?

class Movie(TypedMapping):  # New feature ?
    author: str
    year: int

@dataclass
class Fixed:
    foo: Movie

    def lock(self) -> None:
        self.foo = MappingProxyType(self.foo)  # Would work

Thanks for your time.

All the best!
Élie.

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: featureDiscussions about new features for Python's type annotations

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions