8 ms·
Buried in the notes for the `typing` module: > “Final” variables, functions, methods and classes. See PEP 591, typing.Final and typing.final(). The final quali
by mintplant 7y ago
Buried in the notes for the `typing` module:
> “Final” variables, functions, methods and classes. See PEP 591, typing.Final and typing.final(). The final qualifier instructs a static type checker to restrict subclassing, overriding, or reassignment:
> pi: Final[float] = 3.1415926536
As I understand it, this means Python now has a way of marking variables as constant (though it doesn't propagate into the underlying values as in the case of C++'s `const`).
The equivalent Java:
final float pi = 3.1415926536;
- xapata 7y agoI don't see the point of `final` without an optimizing compiler. Name mangling is sufficient for stashing references to avoid accidental side-effects of overriding.
- eru 7y agoYou can guard yourself against overriding in the same module this way, too. For name mangling, I think you need to start your variable with underscores, and then it won't be accessible for reading outside the module either?
- Sean1708 7y agoFor modules you can access the variable just fine, but for classes you need to use the mangled name: $ cat >foo.py __FOO = 1 class Foo: __FOO = 2 $ cat >bar.py import foo print(foo.__FOO) print(foo.Foo()._Foo__FOO) $ python3 bar.py 1 2
- xapata 7y agoNope, you don't need to start the name with underscores. class Foo: bar = 'public' __bar = bar # stashed
- spott 7y agoThe thing is, it is only enforced in mypy... code that modifies a Final object (pi = 3 for example) later on will run fine.
- dharmab 7y agoCorrect- as usual the annotation indicates intent, but is not enforced at runtime.