From 9d5ec5e3bc01c6174dea048e118edee579c36565 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Sat, 7 Feb 2026 23:06:23 +0900 Subject: fix(style): fix codeblock style for rouge --- .../python-unbound-local-error/index.html | 51 ++++++++++------------ 1 file changed, 24 insertions(+), 27 deletions(-) (limited to 'services/nuldoc/public/blog/posts/2021-10-02/python-unbound-local-error/index.html') diff --git a/services/nuldoc/public/blog/posts/2021-10-02/python-unbound-local-error/index.html b/services/nuldoc/public/blog/posts/2021-10-02/python-unbound-local-error/index.html index 22d4740b..b712c378 100644 --- a/services/nuldoc/public/blog/posts/2021-10-02/python-unbound-local-error/index.html +++ b/services/nuldoc/public/blog/posts/2021-10-02/python-unbound-local-error/index.html @@ -15,7 +15,7 @@ 【Python】 クロージャとUnboundLocalError: local variable 'x' referenced before assignment|REPL: Rest-Eat-Program Loop - +
@@ -75,14 +75,13 @@ Python でクロージャを作ろうと、次のようなコードを書いた。

-
def f():
-    x = 0
-    def g():
-        x += 1
-    g()
-
-f()
-
+
def f(): +
x = 0 +
def g(): +
x += 1 +
g() +
+
f()

関数 g から 関数 f のスコープ内で定義された変数 x を参照し、それに 1 を足そうとしている。 これを実行すると x += 1 の箇所でエラーが発生する。 @@ -96,29 +95,27 @@ local変数 x が代入前に参照された、とある。これは、fx を参照するのではなく、新しく別の変数を g 内に作ってしまっているため。前述のコードを宣言と代入を便宜上分けて書き直すと次のようになる。var を変数宣言のための構文として擬似的に利用している。

-
# 注: var は正しい Python の文法ではない。上記参照のこと
-def f():
-  var x           #  f の local変数 'x' を宣言
-  x = 0           #  x に 0 を代入
-  def g():        #  f の内部関数 g を定義
-      var x       #  g の local変数 'x' を宣言
-      #  たまたま f にも同じ名前の変数があるが、それとは別の変数
-      x += 1      #  x に 1 を加算 (x = x + 1 の糖衣構文)
-      #  加算する前の値を参照しようとするが、まだ代入されていないためエラー
-  g()
-
+
# 注: var は正しい Python の文法ではない。上記参照のこと +
def f(): +
var x # f の local変数 'x' を宣言 +
x = 0 # x に 0 を代入 +
def g(): # f の内部関数 g を定義 +
var x # g の local変数 'x' を宣言 +
# たまたま f にも同じ名前の変数があるが、それとは別の変数 +
x += 1 # x に 1 を加算 (x = x + 1 の糖衣構文) +
# 加算する前の値を参照しようとするが、まだ代入されていないためエラー +
g()

当初の意図を表現するには、次のように書けばよい。

-
def f():
-    x = 0
-    def g():
-        nonlocal x   ## (*)
-        x += 1
-    g()
-
+
def f(): +
x = 0 +
def g(): +
nonlocal x ## (*) +
x += 1 +
g()

(*) のように、nonlocal を追加する。これにより一つ外側のスコープ (g の一つ外側 = f) で定義されている x を探しに行くようになる。 -- cgit v1.3-1-g0d28