'Python equivalent of `final field` in java in dataclass

Is it possible to have something like

class MyAbstract {
   final int myFieldSomebodyHasToDefine;
}


class MyAbstractImplementation extends MyAbstract {
   final int myFieldSomebodyHasToDefine = 5;
}

using dataclasses in python?



Solution 1:[1]

If you are working with a python interpreter before version 3.8, there is no straightforward way. However, since python 3.8, the final decorator has been added to the language. After importing it from the typing module in python, you can use it for methods and classes. You may also use FINAL type for values.

Here is an example

from typing import final, Final


@final
class Base:
    @final
    def h(self)->None:
        print("old")


class Child(Base):
    # Bad overriding
    def h(self) -> None:
        print("new")


if __name__ == "__main__":
    b = Base()
    b.h()
    c = Child()
    c.h()
    RATE: Final = 3000
    # Bad value assignment
    RATE = 7
    print(RATE)

Important note: Python does not force the developer with final and FINAL. You can yet change the values upon your wish. The decorators of mostly informative for developers.

For more information, you may visit: https://peps.python.org/pep-0591/

Update: This is also an instance for dataclass

@dataclass
class Item:
    """Class for keeping track of an item in inventory."""
    price: float
    quantity_on_hand: int = 0
    name:Final[str] = "ItemX"

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand

As you can see, name is a final field. However, you must put the final values with a default value below all of the fields without an initial value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1