メインコンテンツへスキップ
見出し画像

【Python 100日チャレンジ】Day 29 - スコープとグローバル変数

    「この変数、なんでここでは使えないの…?」
    そんな経験ありませんか?
    それはスコープ(変数の有効範囲)の問題です🔍

    たとえば、関数の中で定義した変数は、その関数の外では使えません👇

    def my_function():
        x = 10  # ローカル変数(関数内だけ有効)
        print(f"関数内: {x}")
    
    my_function()  # 関数内: 10
    # print(x)  # ❌ NameError: 関数外では使えない!

    変数には「使える範囲」があり、
    それを理解することでバグを防ぎ、
    より安全なコードが書けるようになります✨

    今日は、スコープの概念から、global/nonlocal キーワード、クロージャ、
    そしてPythonの変数検索ルール(LEGB)まで体系的に学びます💡

    (読了目安:30分 ⭐⭐⭐)

    🎯 今日の学習目標

    1. 変数スコープの概念を理解する

    2. ローカル変数とグローバル変数を区別する

    3. globalとnonlocalキーワードを使う

    4. クロージャとスコープを活用する

    5. LEGBルールとスコープチェーンを理解する

    📚 事前知識


    🎯 学習目標 1: 変数スコープの概念を理解する

    一言説明

    スコープ(Scope) = 変数が有効な範囲、変数を使える領域

    変数ごとに使える範囲が決まっています。

    実生活の比喩

    🏢 会社の入館証:
    
    グローバル変数 = 全館入館証
    - すべてのフロア、すべての部屋に入れる
    
    ローカル変数 = 部署別入館証
    - その部署の部屋だけ入れる
    - 他の部署では使えない

    🎯 学習目標 2: ローカル変数とグローバル変数を区別する

    基本概念

    def my_function():
        x = 10  # ローカル変数(関数内だけ有効)
        print(f"関数内: {x}")
    
    my_function()  # 関数内: 10
    
    # print(x)  # ❌ NameError: 関数外では x を使えない!

    ローカル変数の特徴

    def greet():
        message = "こんにちは!"  # greet関数のローカル変数
        print(message)
    
    def farewell():
        message = "さようなら!"  # farewell関数のローカル変数
        print(message)
    
    greet()      # こんにちは!
    farewell()   # さようなら!
    
    # 各関数のmessageは別々の変数!

    パラメータもローカル変数

    def calculate(a, b):  # a, bはローカル変数
        result = a + b    # resultもローカル変数
        return result
    
    print(calculate(10, 20))  # 30
    
    # print(a)       # ❌ NameError
    # print(b)       # ❌ NameError
    # print(result)  # ❌ NameError

    グローバル変数の基本

    x = 100  # グローバル変数(どこからでもアクセス可能)
    
    def show_x():
        print(f"関数内: {x}")
    
    show_x()          # 関数内: 100
    print(f"関数外: {x}")  # 関数外: 100

    グローバル変数の読み取り vs 変更

    count = 0  # グローバル変数
    
    def show_count():
        print(count)  # ✅ 読み取りはOK
    
    def increment_wrong():
        count = count + 1  # ❌ UnboundLocalError!
        # Pythonはcountをローカル変数とみなす
    
    def increment_right():
        global count  # ✅ グローバル変数使用を宣言
        count = count + 1
    
    show_count()      # 0
    increment_right()
    show_count()      # 1

    同じ名前の変数

    x = 100  # グローバル変数
    
    def my_function():
        x = 10  # ローカル変数(グローバル変数と名前が同じだけで、別の変数!)
        print(f"関数内: {x}")
    
    my_function()  # 関数内: 10(ローカル変数を使用)
    print(f"関数外: {x}")  # 関数外: 100(グローバル変数を使用)

    グローバル変数の隠蔽 (Shadowing)

    name = "グローバル"  # グローバル変数
    
    def show_name():
        name = "ローカル"  # グローバル変数を隠すローカル変数
        print(name)
    
    show_name()  # ローカル
    print(name)  # グローバル

    🎯 学習目標 3: globalとnonlocalキーワードを使う

    基本的な使い方

    counter = 0  # グローバル変数
    
    def increment():
        global counter  # 「グローバル変数counterを使うよ!」
        counter += 1
    
    def decrement():
        global counter
        counter -= 1
    
    print(counter)  # 0
    increment()
    print(counter)  # 1
    increment()
    print(counter)  # 2
    decrement()
    print(counter)  # 1

    複数のグローバル変数宣言

    x = 0
    y = 0
    
    def update_both():
        global x, y  # 複数の変数を一度に
        x = 10
        y = 20
    
    update_both()
    print(x, y)  # 10 20

    global なしで変更を試みる

    score = 0
    
    def add_score(points):
        # ❌ globalなしで変更するとエラー!
        # score = score + points  # UnboundLocalError
    
        # ✅ 正しい方法
        global score
        score = score + points
    
    add_score(10)
    print(score)  # 10

    nonlocal キーワード

    ネスト関数での変数

    def outer():
        count = 0  # outer関数のローカル変数
    
        def inner():
            nonlocal count  # 「外側の関数のcountを使うよ!」
            count += 1
            print(f"inner: {count}")
    
        inner()
        inner()
        print(f"outer: {count}")
    
    outer()
    # inner: 1
    # inner: 2
    # outer: 2

    global vs nonlocal の違い

    x = 100  # グローバル変数
    
    def outer():
        x = 10  # outerのローカル変数
    
        def inner_with_nonlocal():
            nonlocal x  # outerのxを変更
            x = 1
    
        def inner_with_global():
            global x  # グローバルxを変更
            x = 1
    
        print(f"outer開始: x = {x}")  # 10
    
        inner_with_nonlocal()
        print(f"nonlocal後: x = {x}")  # 1
    
    outer()
    print(f"グローバル: x = {x}")  # 100(影響なし)
    
    # globalテスト
    def outer2():
        x = 10
    
        def inner_with_global():
            global x
            x = 1
    
        print(f"outer2開始: x = {x}")  # 10
        inner_with_global()
        print(f"global後: x = {x}")  # 10(影響なし)
    
    outer2()
    print(f"グローバル: x = {x}")  # 1(変更された!)

    🎯 学習目標 4: クロージャとスコープを活用する

    クロージャとは?

    クロージャ(Closure) = 関数が定義された環境の変数を記憶すること

    ネスト関数が外部関数の変数を記憶して使える強力なパターンです。

    基本例

    def outer():
        message = "Hello"  # Enclosing変数
    
        def inner():
            print(message)  # 外部関数の変数にアクセス可能!
    
        return inner
    
    my_func = outer()
    my_func()  # Hello - outer()が終わってもmessageを記憶!

    クロージャカウンター

    def create_counter():
        """カウンター生成器(クロージャパターン)"""
        count = 0  # Enclosing変数
    
        def increment():
            nonlocal count
            count += 1
            return count
    
        def decrement():
            nonlocal count
            count -= 1
            return count
    
        def get_count():
            return count
    
        return increment, decrement, get_count
    
    # カウンター生成
    inc, dec, get = create_counter()
    
    print(inc())  # 1
    print(inc())  # 2
    print(inc())  # 3
    print(dec())  # 2
    print(get())  # 2

    クロージャを使う理由

    1. データ隠蔽:外部から直接アクセスできないprivate変数を作成

    2. 状態維持:関数呼び出し間で状態を保存

    3. ファクトリパターン:設定が異なる複数の関数を生成

    def make_multiplier(n):
        """nを掛ける関数を生成"""
        def multiply(x):
            return x * n
        return multiply
    
    times3 = make_multiplier(3)
    times5 = make_multiplier(5)
    
    print(times3(10))  # 30
    print(times5(10))  # 50

    🎯 学習目標 5: LEGBルールとスコープチェーンを理解する

    変数検索順序 (LEGB)

    Pythonが変数を探す順序:

    1. Local (ローカル): 現在の関数内

    2. Enclosing (エンクロージング): ネスト関数の外側関数

    3. Global (グローバル): モジュール全体

    4. Built-in (ビルトイン): Python標準関数・変数

    # Built-in
    len, print, max など
    
    # Global
    x = "global"
    
    def outer():
        # Enclosing
        x = "enclosing"
    
        def inner():
            # Local
            x = "local"
            print(x)  # "local" 出力
    
        inner()
        print(x)  # "enclosing" 出力
    
    outer()
    print(x)  # "global" 出力

    LEGB 実践例

    x = "Global X"
    
    def outer():
        x = "Enclosing X"
    
        def inner():
            x = "Local X"
            print(f"1. {x}")  # Local X
    
        def inner2():
            print(f"2. {x}")  # Enclosing X
    
        inner()
        inner2()
        print(f"3. {x}")  # Enclosing X
    
    outer()
    print(f"4. {x}")  # Global X

    Built-in スコープ注意事項

    # Built-in関数 max
    print(max([1, 2, 3, 4, 5]))  # 5
    
    def my_function():
        # ❌ maxを変数で上書きするとBuilt-in関数が使えない!
        max = 100
        print(max)  # 100
    
        # print(max([1, 2, 3]))  # TypeError: 'int' object is not callable
    
    my_function()
    
    # 関数外ではまだ使える
    print(max([1, 2, 3, 4, 5]))  # 5

    スコープチェーン可視化

    # Built-in: len, print, max, min, sum...
    
    count = 0  # Global
    
    def outer():
        total = 0  # Enclosing
    
        def inner():
            result = 0  # Local
    
            # 検索順序:
            # 1. Local (resultを発見)
            # 2. Enclosing (totalを発見)
            # 3. Global (countを発見)
            # 4. Built-in (printを発見)
            print(f"{result}, {total}, {count}")
    
        inner()
    
    outer()

    💡 実践例

    例1: ゲームスコアシステム

    score = 0
    high_score = 0
    
    def add_points(points):
        """スコア追加"""
        global score, high_score
    
        score += points
    
        if score > high_score:
            high_score = score
    
        print(f"現在のスコア: {score}, ハイスコア: {high_score}")
    
    def reset_score():
        """スコアリセット"""
        global score
        score = 0
        print("スコアがリセットされました。")
    
    # ゲームプレイ
    add_points(10)    # 現在のスコア: 10, ハイスコア: 10
    add_points(20)    # 現在のスコア: 30, ハイスコア: 30
    reset_score()     # スコアがリセットされました。
    add_points(15)    # 現在のスコア: 15, ハイスコア: 30

    例2: 設定マネージャー

    config = {
        "theme": "light",
        "language": "ja"
    }
    
    def get_config(key):
        """設定値取得"""
        return config.get(key, "設定なし")
    
    def set_config(key, value):
        """設定値変更"""
        global config
        config[key] = value
        print(f"{key} = {value}に設定されました。")
    
    def reset_config():
        """設定初期化"""
        global config
        config = {
            "theme": "light",
            "language": "ja"
        }
        print("設定が初期化されました。")
    
    # 使用
    print(get_config("theme"))       # light
    set_config("theme", "dark")      # theme = darkに設定されました。
    print(get_config("theme"))       # dark

    💡 実践のコツと注意点

    Tip1. グローバル変数最小化の原則 (Best Practice)

    ❌ 悪い例: グローバル変数に過度に依存

    user_name = ""
    user_age = 0
    user_email = ""
    
    def update_user(name, age, email):
        global user_name, user_age, user_email
        user_name = name
        user_age = age
        user_email = email

    ✅ 良い例1: 戻り値を活用

    def create_user(name, age, email):
        return {
            "name": name,
            "age": age,
            "email": email
        }
    
    user = create_user("田中太郎", 25, "tanaka@example.com")

    ✅ 良い例2: クラスを使用(より良い方法)

    class User:
        def __init__(self, name, age, email):
            self.name = name
            self.age = age
            self.email = email
    
    user = User("田中太郎", 25, "tanaka@example.com")

    理由: グローバル変数はデバッグを難しくし、複数の関数で同時に変更すると予測困難なバグが発生します。

    Tip 2. 定数は大文字で (Convention)

    # ✅ 定数は大文字 + アンダースコア
    MAX_RETRY_COUNT = 3
    API_TIMEOUT = 30
    DEFAULT_PORT = 8080
    
    def connect(port=DEFAULT_PORT):
        print(f"ポート{port}で接続中...")
    
    connect()  # ポート8080で接続中...

    理由: 大文字で書くと「この変数は変更すべきでない」という意図を明確に伝えられます(Pythonには定数キーワードがありません)。

    Tip 3. 可変オブジェクト(list、 dict) vs 不変オブジェクト(int、 str)

    # リストはglobalなしでも変更可能
    my_list = [1, 2, 3]
    
    def append_item(item):
        my_list.append(item)  # ✅ 変更OK
    
    append_item(4)
    print(my_list)  # [1, 2, 3, 4]
    
    # ただし再代入はglobalが必要
    def replace_list():
        global my_list  # ✅ 必須!
        my_list = [5, 6, 7]
    
    replace_list()
    print(my_list)  # [5, 6, 7]
    
    # 数値・文字列は不変オブジェクトなので常にglobalが必要
    count = 0
    
    def increment():
        global count  # ✅ 必須!
        count += 1
    
    increment()
    print(count)  # 1

    核心: リストの**メソッド(append, extendなど)**はglobalなしで呼び出し可能ですが、**再代入(`=`)**はglobalが必要です。

    Tip 4. nonlocal はネスト関数でのみ

    # ✅ nonlocalはネスト関数(nested function)でのみ意味がある
    def outer():
        count = 0
    
        def increment():
            nonlocal count
            count += 1
            return count
    
        print(increment())  # 1
        print(increment())  # 2
    
    outer()
    
    # ❌ 最上位レベルでは使用不可
    # count = 0
    # nonlocal count  # SyntaxError

    理由:nonlocalは「すぐ外側の関数の変数」を参照するキーワードです。グローバル変数にはglobalを使います。

    Tip 5. 関数パラメータで渡す(最も推奨)

    ❌ グローバル変数使用

    total = 0
    
    def add_to_total(value):
        global total
        total += value
    
    add_to_total(10)
    add_to_total(20)
    print(total)  # 30

    ✅ パラメータと戻り値を使用(よりクリーン!)

    def add(current, value):
        return current + value
    
    total = 0
    total = add(total, 10)
    total = add(total, 20)
    print(total)  # 30

    理由:関数が独立しテストしやすく、副作用(side effect)がないので安全です。

    Tip 6. デバッグヒント: locals()とglobals()

    x = 100  # グローバル変数
    
    def my_function():
        y = 200  # ローカル変数
    
        print("ローカル変数:")
        print(locals())  # {'y': 200}
    
        print("\nグローバル変数:")
        print(globals())  # {..., 'x': 100, ...}
    
    my_function()

    活用: スコープ問題が発生したら`locals()`と`globals()`で現在使用可能な変数を確認できます。

    Tip 7. UnboundLocalError 注意

    count = 10  # グローバル変数
    
    def increment():
        # ❌ このコードはエラー!
        # count = count + 1  # UnboundLocalError
    
        # Pythonは関数内でcountに値を代入するのを見て
        # countをローカル変数とみなします。
        # しかしcount + 1を計算するときはまだローカル変数countが定義されていません!
    
        # ✅ 解決策1: globalを使用
        global count
        count = count + 1
    
    # ✅ 解決策2: 新しい変数を使用
    def increment2():
        new_count = count + 1
        return new_count

    核心: Pythonは関数全体をスキャンして変数代入があればローカル変数とみなします。

    Tip 8. クロージャでprivate変数を実装

    def create_bank_account(initial_balance):
        """クロージャを使った銀行口座シミュレーション"""
        balance = initial_balance  # private変数
    
        def deposit(amount):
            nonlocal balance
            balance += amount
            return balance
    
        def withdraw(amount):
            nonlocal balance
            if balance >= amount:
                balance -= amount
                return balance
            else:
                return "残高不足"
    
        def get_balance():
            return balance
    
        # 辞書で返す
        return {
            "deposit": deposit,
            "withdraw": withdraw,
            "get_balance": get_balance
        }
    
    # 使用
    account = create_bank_account(1000)
    print(account["get_balance"]())  # 1000
    print(account["deposit"](500))   # 1500
    print(account["withdraw"](200))  # 1300

    メリット: balance変数に直接アクセスできないのでデータ整合性を保証します。

    Tip 9. Built-in関数名の上書き禁止

    # ❌ 悪い例
    max = 10  # Built-in関数maxを変数として使用
    # print(max([1, 2, 3]))  # TypeError: 'int' object is not callable
    
    # ✅ 良い例
    maximum = 10
    print(max([1, 2, 3]))  # 3
    
    # よく上書きされるBuilt-in関数
    # list, dict, str, int, float, max, min, sum, len, id, type, input, print

    理由: Built-in関数を変数として使用すると、その関数をもう使えなくなります。

    Tip 10. ループ変数は関数スコープに従う

    # Pythonのforループ変数は関数スコープ!
    def process_numbers():
        for i in range(3):
            print(i)
    
        # ✅ ループが終わってもiにはまだアクセス可能
        print(f"最後のi値: {i}")  # 2
    
    process_numbers()
    # 0
    # 1
    # 2
    # 最後のi値: 2

    参考: 一部の言語(C, Java)はブロックスコープを使いますが、Pythonは関数スコープのみです。

    Tip 11. ラムダ関数もクロージャを作れる

    def make_multiplier(n):
        # ラムダ関数がnを記憶(クロージャ)
        return lambda x: x * n
    
    times2 = make_multiplier(2)
    times5 = make_multiplier(5)
    
    print(times2(10))  # 20
    print(times5(10))  # 50

    活用: 簡単なファクトリ関数を作るときに便利です。

    Tip 12. global キーワードは関数最上部で宣言

    count = 0
    
    def increment():
        # ✅ 関数開始部分で宣言
        global count
    
        # 複数行のコード...
        count += 1
        count *= 2
    
        return count
    
    # ❌ 途中で宣言すると可読性が下がる
    def bad_example():
        print("処理中...")
        global count  # 下の方にあって発見しにくい
        count += 1

    理由: 関数開始部分で宣言するとグローバル変数使用の有無を一目で把握できます。

    Tip 13. LEGBの順序を活用したBuilt-in関数復元

    # Built-in関数の再定義(慎重に使用)
    def custom_max(*args):
        """max関数のカスタムバージョン"""
        import builtins  # Built-inスコープへのアクセス
    
        # Built-in maxを使用
        result = builtins.max(*args)
        print(f"最大値: {result}")
        return result
    
    custom_max(1, 5, 3, 9, 2)  # 最大値: 9

    活用: Built-in関数を変数で上書きしてしまったとき`builtins`モジュールで元の関数にアクセスできます。

    Tip 14. ネスト関数の利点: ヘルパー関数のカプセル化

    def process_data(data):
        """データ処理関数"""
    
        # 内部ヘルパー関数(外部からアクセス不可)
        def validate(item):
            return isinstance(item, int) and item > 0
    
        def transform(item):
            return item * 2
    
        # メインロジック
        valid_data = [x for x in data if validate(x)]
        result = [transform(x) for x in valid_data]
        return result
    
    print(process_data([1, -2, 3, "4", 5]))  # [2, 6, 10]
    
    # ❌ validate, transform関数は外部からアクセス不可
    # validate(10)  # NameError

    メリット: 関連するヘルパー関数をカプセル化して名前空間の汚染を防ぎます。

    Tip 15. グローバル変数が必要な場合: 設定と状態

    ✅ グローバル変数を使っても良い場合

    1. アプリケーション設定(変更されない)

    DEBUG_MODE = True
    DATABASE_URL = "postgresql://localhost/mydb"
    MAX_CONNECTIONS = 100

    2. アプリケーション状態(慎重に)

    _connection_pool = None  # private変数(前に_を付ける)
    
    def get_connection():
        global _connection_pool
        if _connection_pool is None:
            _connection_pool = "Connection Pool Created"
        return _connection_pool

    3. キャッシュ(パフォーマンス最適化)

    _cache = {}
    
    def expensive_function(n):
        if n in _cache:
            return _cache[n]
    
        # コストの高い計算
        result = sum(range(n))
        _cache[n] = result
        return result

    ガイドライン:

    • 設定値は大文字定数で

    • 状態変数は`_`で始める(private慣例)

    • クラスやモジュールでカプセル化する方がより良い


    🔧 トラブルシューティング

    問題1: UnboundLocalError

    症状:

    count = 0
    
    def increment():
        count = count + 1  # UnboundLocalError!

    原因:count = ...があるとPythonはcountをローカル変数とみなす

    解決:

    count = 0
    
    def increment():
        global count  # グローバル変数宣言
        count = count + 1

    問題2: グローバル変数の読み取りはできるが書き込みができない

    症状:

    value = 100
    
    def show():
        print(value)  # ✅ 読み取りOK
    
    def modify():
        value = 200  # ✅ 構文エラーはないが、グローバル変数が変わらない!
    
    show()    # 100
    modify()
    show()    # まだ100

    解決:

    def modify():
        global value  # グローバル変数宣言
        value = 200
    
    modify()
    show()  # 200

    問題3: nonlocal 誤用

    症状:

    def outer():
        def inner():
            nonlocal x  # SyntaxError: no binding for nonlocal 'x' found
            x = 10

    原因:nonlocalは既存のEnclosing変数にのみ使用可能

    解決:

    def outer():
        x = 0  # まず変数を宣言
    
        def inner():
            nonlocal x
            x = 10
    
        inner()
        print(x)  # 10
    
    outer()

    🧪 練習問題

    問題1: 銀行口座システム

    次の要件を満たす銀行口座システムを作成してください。

    • 残高(balance)をグローバル変数で管理

    • deposit(金額):入金

    • withdraw(金額):出金(残高不足時はエラーメッセージ)

    • get_balance():残高照会

    💡 ヒント

    1. globalキーワードの使い方を復習

    2. 条件分岐でbalance >= amountをチェック

    3. 数値フォーマットには`{:,}`を使用

    ✅ 正解

    balance = 10000  # 初期残高
    
    def deposit(amount):
        """入金"""
        global balance
        balance += amount
        print(f"{amount:,}円入金完了。残高: {balance:,}円")
    
    def withdraw(amount):
        """出金"""
        global balance
        if amount > balance:
            print(f"残高不足!現在残高: {balance:,}円")
        else:
            balance -= amount
            print(f"{amount:,}円出金完了。残高: {balance:,}円")
    
    def get_balance():
        """残高照会"""
        print(f"現在残高: {balance:,}円")
        return balance
    
    # テスト
    get_balance()      # 現在残高: 10,000円
    deposit(5000)      # 5,000円入金完了。残高: 15,000円
    withdraw(3000)     # 3,000円出金完了。残高: 12,000円
    withdraw(20000)    # 残高不足!現在残高: 12,000円
    get_balance()      # 現在残高: 12,000円

    問題2: ネストカウンター

    次の要件を満たすネストカウンター関数を作成してください。

    • outer関数にcount変数

    • inner関数でnonlocalでcount変更

    • increment()とget_count()を返す

    💡 ヒント

    1. outer関数でcount = startで初期化

    2. 内部関数でnonlocal countを宣言

    3. 複数の関数を返すにはタプルを使用

    ✅ 正解

    def create_counter(start=0):
        """カウンター生成器"""
        count = start  # Enclosing変数
    
        def increment(step=1):
            """カウント増加"""
            nonlocal count
            count += step
            return count
    
        def get_count():
            """現在のカウント照会"""
            return count
    
        return increment, get_count
    
    # テスト
    inc, get = create_counter(10)
    
    print(get())      # 10
    print(inc())      # 11
    print(inc())      # 12
    print(inc(5))     # 17
    print(get())      # 17
    
    # 新しいカウンター
    inc2, get2 = create_counter(100)
    print(get2())     # 100
    print(inc2(10))   # 110

    ❓ よくある質問 (FAQ)

    Q1. グローバル変数とローカル変数の名前が同じならどうなりますか?

    ローカル変数が優先されます。 関数内部ではローカル変数を使用し、グローバル変数は隠されます (Shadowing)。

    x = "グローバル"
    
    def my_function():
        x = "ローカル"  # グローバルxを隠す
        print(x)   # "ローカル" 出力
    
    my_function()
    print(x)  # "グローバル" 出力(グローバル変数は影響なし)

    解決方法: グローバル変数を使うには`global`キーワードを明示してください。

    x = "グローバル"
    
    def my_function():
        global x
        print(x)   # "グローバル" 出力
        x = "変更された"
    
    my_function()
    print(x)  # "変更された" 出力

    Q2. globalとnonlocalの違いは何ですか?

    • global:モジュール最上位のグローバル変数を変更

    • nonlocal:ネスト関数で外側の関数の変数を変更

    count = 0  # グローバル変数
    
    def outer():
        total = 0  # Enclosing変数
    
        def inner():
            # global countを使うとモジュールのグローバル変数を変更
            global count
            count += 1
    
            # nonlocal totalを使うとouterの変数を変更
            nonlocal total
            total += 1
    
            print(f"count={count}, total={total}")
    
        inner()
        inner()
    
    outer()
    # count=1, total=1
    # count=2, total=2

    簡単まとめ:

    • global:最も外側(モジュール)の変数

    • nonlocal:一段階外側(enclosing)関数の変数

    Q3. 関数内でグローバル変数を読み取るだけならglobalなしで可能ですか?

    はい、可能です! `global`はグローバル変数を変更するときだけ必要です。

    message = "こんにちは"
    
    def greet():
        # globalなしで読み取り可能
        print(message)
    
    greet()  # "こんにちは" 出力
    
    def change():
        # ❌ globalなしで変更を試みる → UnboundLocalError
        # message = message + "!"  # エラー!
    
        # ✅ globalキーワード使用
        global message
        message = message + "!"
    
    change()
    print(message)  # "こんにちは!" 出力

    ルール:

    • 読み取りのみ:global不要

    • 変更する場合:global必須

    Q4. LEGB順に同じ名前の変数があるとどうなりますか?

    最も近いスコープの変数が使用されます。 Localが最も優先順位が高いです。

    x = "Global"
    
    def outer():
        x = "Enclosing"
    
        def inner():
            x = "Local"
            print(x)  # "Local" 出力(Lが最優先)
    
        inner()
        print(x)  # "Enclosing" 出力(Eが優先)
    
    outer()
    print(x)  # "Global" 出力

    検索順序:

    1. Local:現在の関数内 → 見つかれば使用

    2. Enclosing:外側の関数 → なければ次へ

    3. Global:モジュールグローバル → なければ次へ

    4. Built-in:Python組み込み → なければNameError

    Q5. クロージャはなぜ使うのですか?グローバル変数との違いは?

    クロージャの利点:

    1. データ隠蔽:外部から直接変更できない

    2. 独立した状態:複数のインスタンスが各自の状態を維持

    3. グローバル汚染防止:グローバル名前空間をクリーンに保つ

    ❌ グローバル変数方式 - 問題が多い

    count1 = 0
    count2 = 0  # カウンター追加のたびにグローバル変数が増える
    
    def inc1():
        global count1
        count1 += 1
        return count1
    
    def inc2():
        global count2
        count2 += 1
        return count2

    ✅ クロージャ方式 - クリーンで安全

    def make_counter():
        count = 0  # 外部から直接アクセス不可!
    
        def increment():
            nonlocal count
            count += 1
            return count
    
        return increment
    
    counter1 = make_counter()
    counter2 = make_counter()  # 独立したカウンター
    
    print(counter1())  # 1
    print(counter1())  # 2
    print(counter2())  # 1(独立!)

    クロージャが優れている理由:

    • 外部でcountを勝手に変更できない(安全性)

    • カウンターを複数作っても互いに独立(拡張性)

    • グローバル変数が増えない(クリーン)

    Q6. Built-in関数名を変数として使うとどうなりますか?

    そのスコープでBuilt-in関数を使えなくなります。

    # ❌ 危険な例: maxを変数として使用
    def calculate():
        max = 100  # Built-in maxを隠す!
        numbers = [1, 2, 3, 4, 5]
    
        # print(max(numbers))  # TypeError: 'int' object is not callable
        # maxが今整数100なので関数ではない!
    
    calculate()
    
    # 関数外ではまだ使える
    print(max([1, 2, 3, 4, 5]))  # 5

    推奨事項: Built-in関数名は変数名として使わないでください!

    よくあるBuilt-in名(避けるべき変数名):

    • list、dict、set、tuple

    • str、int、float、bool

    • len、max、min、sum

    • print、input、open

    • range、zip、map、filter

    Q7. nonlocalは複数段階の外側関数にもアクセス可能ですか?

    はい、可能です! nonlocalは最も近いEnclosingスコープの変数を探します。

    def level1():
        x = "Level 1"
    
        def level2():
            x = "Level 2"
    
            def level3():
                # level2のxを変更
                nonlocal x
                x = "Modified in Level 3"
                print(f"Level 3: {x}")
    
            level3()
            print(f"Level 2: {x}")  # "Modified in Level 3"
    
        level2()
        print(f"Level 1: {x}")  # "Level 1"(影響なし)
    
    level1()

    複数段階のスキップ:

    def outer():
        x = "Outer"
    
        def middle():
            # xを宣言しない
    
            def inner():
                # middleにxがないのでouterのxを変更
                nonlocal x
                x = "Modified"
    
            inner()
    
        middle()
        print(x)  # "Modified"
    
    outer()

    ルール:`nonlocal`は最も近いEnclosingスコープで変数を探します。

    Q8. ラムダ関数でもスコープルールは同じですか?

    はい、同じです! ラムダも関数なのでLEGBルールに従います。

    x = 10  # Global
    
    def outer():
        x = 20  # Enclosing
    
        # ラムダでもLEGB順で検索
        func = lambda y: x + y  # Enclosingのx (20) を使用
    
        return func
    
    f = outer()
    print(f(5))  # 25 (20 + 5)

    クロージャも可能:

    def make_adder(n):
        # ラムダがnを記憶(クロージャ)
        return lambda x: x + n
    
    add10 = make_adder(10)
    add20 = make_adder(20)
    
    print(add10(5))  # 15
    print(add20(5))  # 25

    注意:ラムダでは`global`や`nonlocal`を使えません(代入文が不可能)。


    📝 今日学んだ内容のまとめ

    1. スコープ:変数が有効な範囲

    2. ローカル変数:関数内部でのみ有効

    3. グローバル変数:どこからでもアクセス可能

    4. global:グローバル変数を変更

    5. nonlocal:Enclosing変数を変更

    6. LEGBルール:Local → Enclosing → Global → Built-in の順で検索

    🔗 関連資料


    📚 以前の学習

    Day 28: ラムダ関数 (lambda)⭐

    前回は、ラムダ関数で簡単な関数を作る方法を学びました!

    📚 次の学習

    Day 30: ミニプロジェクト - 計算機 ⭐⭐⭐

    次回は、今まで学んだすべてを活用した計算機プロジェクトを作ります!

    📚 シリーズをまとめて読む

    Python 100日チャレンジの全記事は、
    マガジン「Python 100日チャレンジ」 でまとめて読めます 😊
    よろしければ、フォローしていただけると嬉しいです!


    🚀 遅いと思った時が一番早い時期です!🚀
    Day 29/100 | Phase 3: 制御文と関数 | #100DaysOfPython

    よんよんわれ
     
     
    ソフトウェアエンジニアです。 ものづくりが好きで、プライベートでも複数のサイドプロジェクトに取り組んでいます。 最近は、AIと自動化を活用したサービス開発に力を入れています。 Note、Xなどでお友達になっていただけたら嬉しいです☺️

    あなたへのおすすめ