I was wondering if there's a way to define within the same "data container" values of mutable/immutable/default values.
by "data container" I mean any things like tuple, dict, class, Enum, dataclass
this example makes my point clear:
if I want to have Page with first_page current_page last_page as values.
if I would go with the dataclass method the implementation would be something like this:
from dataclasses import dataclass
@dataclass(slots=True)
class Pages:
first_page: int = 0 # need to be immutable
current_page: int # need to be initialized and mutable
last_page: int # need to be initialized and immutable
can this be done? or is there a way to do it?
For a class, you can use getters and setters. For example, to have
first_pagebe immutable, you can create a quasi-private property called_first_page(it's not actually private in Python), that you access via the (getter) propertyfirst_pageattribute:With this, you can get
first_page, but if you try settingfirst_pageyou will get anAttributeError:You could have an equivalent
setterattribute that explicitly returns a message thatfirst_pageis immuatble and does nothing, e.g.,:For values that you want to be mutable, you can just set the class attributes as you normally would, or (as above) use the
@propertyand@setterdecorated functions to set the equivalent quasi-private attributes.