Python 3.8では、代入式が導入され、条件文とラムダで値を代入できるようになりました。
if x := True:
print(x)
ただし、このようなことをしようとしているため、これは属性の割り当てには拡張されないようです。
from typing import NamedTuple
class Test(NamedTuple):
field : bool
test = Test(field=False)
if test.field := True:
print(test.field)
次のエラーが発生します。
SyntaxError: cannot use named assignment with attribute
(代入式ではなく)代入ステートメントの属性を更新することだけが本当に可能ですか?そうであれば、なぜこの制限がありますか?
ペップから:
代入式と代入文の違い
最も重要なの
:=
は、が式であるため、ラムダ関数や内包表記など、ステートメントが不正なコンテキストで使用できることです。逆に、代入式は、代入ステートメントにある高度な機能をサポートしていません。
- 単一以外の単一の割り当てターゲット
NAME
はサポートされていません。# No equivalent a[i] = x self.rest = []
複雑すぎることを避けるために作られたようです(これはおそらくどこかで完全なステートメントに変換する必要があることを示しています)。また、これはすでに次の方法で実現できますsetattr
。
# This is not that readable, but has the same semantics as what you asked for
if (setattr(test, 'field', new_test_field := ...), new_test_field)[1]:
...
# More readable with a helper function
def set_member(obj, member_name, new_value):
setattr(obj, member_name, new_value)
return new_value
if set_member(test, 'field', ...):
...
# But you might have wanted to check the new `test.field`
# instead of what you assigned it (In case it was a getter/setter descriptor)
def set_member(obj, member_name, new_value):
setattr(obj, member_name, new_value)
return getattr(obj, member_name)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加