0
0

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のスコープについて

Last updated at Posted at 2025-03-06

Pythonのスコープについてメモ

Pythonを学んでいると必ず出てくる「スコープ」という言葉。
これは「変数がどこから見えて、どこで使えるか」を示すルールのことです。

特に関数内と関数外で同じ変数を使うときや、関数の中に関数があるときにはスコープを理解していないと混乱しやすいです。

今回は、Pythonのスコープを基本から応用までまとめて解説します。


Pythonのスコープ「LEGBルール」とは?

Pythonには、次の4つのスコープがあります。

スコープ名 説明 具体例
Local 関数内で作られた変数 関数の中のx
Enclosing 外側の関数(ネスト時) 関数の中に関数がある場合の外側のx
Global 関数の外(モジュール全体) ファイルの最初に作ったx
Builtin Pythonが元から持っているもの print(), len()など

具体例で理解するスコープ

Localスコープ

関数の中で作った変数は、その関数の外からは見えません。

def my_func():
    x = 100

my_func()
print(x)  # NameError: name 'x' is not defined

Enclosingスコープ(関数をネストした場合)

関数の中に関数を作ると、外側関数の変数を内側関数から使うことができます。

def outer():
    x = "外側"

    def inner():
        print(x)  # 外側のxが見える
    inner()

outer()

Globalスコープ

関数の外で作った変数は、関数内でも読み取ることはできます

x = 10

def my_func():
    print(x)  # グローバルのxが見える

my_func()

Builtinスコープ

Pythonが最初から持っているprint()len()などの関数は、どこからでも使えます。

print(len("hello"))  # 5

globalとnonlocalの使い方

関数内からグローバル変数を書き換えるには?

globalを使います。

x = 10

def update_global():
    global x
    x = 100

update_global()
print(x)  # 100

ネスト関数で外側関数の変数を書き換えるには?

nonlocalを使います。

def outer():
    x = 10

    def inner():
        nonlocal x
        x = 100

    inner()
    print(x)  # 100

outer()

スコープまとめ表

やりたいこと 必要な宣言 スコープ
関数内でローカル変数を使う なし Local
内側関数から外側関数の変数を更新 nonlocal Enclosing
関数内からグローバル変数を更新 global Global
関数内でグローバル変数を読むだけ なし Builtin

まとめ

  • 関数の中で作った変数は「Localスコープ」 で、外から見えない
  • 関数の外で作った変数は「Globalスコープ」 で、関数の中からも読める
  • ネスト関数なら「Enclosingスコープ」が使える
  • globalでグローバルを書き換え
  • nonlocalで外側のローカルを書き換え

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?