Replies: 3 comments 4 replies
-
You can use
|
Beta Was this translation helpful? Give feedback.
-
I am receiving large json objects which I am parsing into dicts/lists/strings/numbers and over time receiving patches to these objects. I apply the patch, and want to provide the new state of the object to my program. This is pure data these are not classes, just native types. To be safe I have to deepcopy this object when I hand it off to make sure future patches can't be corrupted by me or anyone else accidentally mutating the data. What would be perfect is if I could return the internal data type marked as readonly, to avoid an expensive copy. Perhaps this situation is more concrete, but similar enough to continue as a discussion. |
Beta Was this translation helpful? Give feedback.
-
strings and numbers are already immutable, for dicts and lists you can use the abstract I do sometimes use a |
Beta Was this translation helpful? Give feedback.
-
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.Example of what this could look like:
Is it possible to define
Readonly
? Maybe the only way is to write a mypy plugin similar to the one for dataclasses?Beta Was this translation helpful? Give feedback.
All reactions