22
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python の Final - 型ヒントで定数と変更できない属性を宣言する。

Last updated at Posted at 2020-01-16

PEP 591 で議論され Python 3.8 から追加されていたようです。

変数

◯ 初期化しないとエラー

from typing import Final

var: Final[int]
# sample.py:3: error: Final name must be initialized with a value

◯ 変更しようとするとエラー

from typing import Final

var: Final[int] = 0
var = 1
# sample.py:4: error: Cannot assign to final name "var"

属性

◯ 初期化しないとエラー

from typing import Final

class Class:
    attr: Final[int]
    # sample.py:4: error: Final name must be initialized with a value

◯ 変更しようとするとエラー

from typing import Final

class Class:
    attr: Final[int]

    def __init__(self, attr):
        self.attr = attr


obj = Class(0)
obj.attr = 1
# sample.py:11: error: Cannot assign to final attribute "attr"
22
13
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?