Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define final classvar variable in python

As you can see in PEP 526 we can define static variable class with ClassVar word. like below

class Starship:
    stats: ClassVar[dict[str, int]] = {} # class variable
    damage: int = 10                     # instance variable

And another typing feature as you can see in PEP 591 we can define constant (readonly) variable with Final word, like below

class Connection:
    TIMEOUT: Final[int] = 10

My question is how to combine these two words to say my class static variable is Final?

for example is below code is valid?

class Connection:
    TIMEOUT: Final[ClassVar[int]] = 10
like image 634
sorosh_sabz Avatar asked Dec 04 '25 17:12

sorosh_sabz


1 Answers

From PEP-591:

Type checkers should infer a final attribute that is initialized in a class body as being a class variable. Variables should not be annotated with both ClassVar and Final.

So you ca just use:

class Connection:
    TIMEOUT: Final[int] = 10
like image 152
juanpa.arrivillaga Avatar answered Dec 06 '25 07:12

juanpa.arrivillaga