Skip to content

Question about read-only types #1348

@maufl

Description

@maufl

Hi, I'm currently trying to find out whether it's possible to have a generic type that works like Readonly in Typescript. While it's built into Typescript, you could also define it yourself using Mapped Types.

So far I did not find a way of doing this. If it's possible at all, then probably using a generic class with a fancy __getattribute__ implementation?

A use case for this would be typing the returned values of libraries like gelidum for example.
I specifically would want to have this to type returned objects from SQLAlchemy sessions that have been expunged. The properties of these objects can still be read, but if you try to set one of them, the change will not be persisted if you commit the session, since the object is not attached to the session. Marking them as read-only would prevent someone from accidentally trying to change them.
An added benefit is that, if you can make a function argument Readonly[User], you also communicate that you will not change the passed argument.

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