回答編集履歴
2
mypy での型検査を考慮して、回答の一部を撤回。(コードが複雑になる為)
test
CHANGED
@@ -12,7 +12,7 @@
|
|
12
12
|
> dataclassで元フォルダの更新を実現するためにはどうしたらいいでしょうか?
|
13
13
|
|
14
14
|
後から設定される path_parent を元に、サブディレクトリを返したいのであれば
|
15
|
-
「プロパティー」として実装すれば目的の挙動になります。
|
15
|
+
~~「プロパティー」として実装すれば目的の挙動になります。~~ (追記: 型検査する場合は、冗長になるので撤回)
|
16
16
|
インスタンス生成時に上書きしたいのであれば、`__post_init__` メソッド内で上書きします。
|
17
17
|
|
18
18
|
|
1
エラーコードを一旦削除
test
CHANGED
@@ -20,42 +20,6 @@
|
|
20
20
|
|
21
21
|
クラス定義部分の記述を短くしたいだけであれば、用途には沿わないかもしれません。
|
22
22
|
|
23
|
-
|
24
|
-
```python
|
25
|
-
from pathlib import Path
|
26
|
-
from dataclasses import dataclass
|
27
|
-
|
28
|
-
@dataclass
|
29
|
-
class SampleConfig:
|
30
|
-
path_parent: Path = Path("src")
|
31
|
-
path_child_a: Path = path_parent / "a"
|
32
|
-
path_child_b: Path = path_parent / "b"
|
33
|
-
path_child_c: Path = path_parent / "c"
|
34
|
-
path_child_d: Path = path_parent / "d"
|
35
|
-
|
36
|
-
for c in "abcd":
|
37
|
-
def _getter(self, c=c) -> Path:
|
38
|
-
return self.path_parent / c
|
39
|
-
|
40
|
-
# 注意(重要): ここの動的フィールド設定は、mypy等の静的コード検査を回避します
|
41
|
-
# 厳格な型チェックが必要な場合は、多少コード量が増えても
|
42
|
-
# ひとつづつ宣言的に記述する方法をお勧めします。
|
43
|
-
locals()[f"path_child_{c}"] = property(_getter)
|
44
|
-
|
45
|
-
del _getter # メソッドが作られるのを回避
|
46
|
-
|
47
|
-
# 型検査の為の関数
|
48
|
-
def print_path(path: Path) -> None:
|
49
|
-
print(path)
|
50
|
-
|
51
|
-
|
52
|
-
config = SampleConfig(Path("test"))
|
53
|
-
print_path(config.path_child_a)
|
54
|
-
|
55
|
-
# 直接代入可 (プロパティを上書き)
|
56
|
-
config.path_child_b = Path("b")
|
57
|
-
|
58
|
-
```
|
59
23
|
|
60
24
|
```python
|
61
25
|
from typing import Any
|