LoginSignup
17
11

More than 5 years have passed since last update.

Pythonのlocals()

Posted at

チラ裏品質。「うえー」ってなったのでメモっとく。

環境は下記の通り (macOS Sierra + pyenv)

Python 3.6.3 (default, Oct 10 2017, 09:48:52)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

locals() はそのローカル名前空間の名前を辞書形式で返すのかと思いきや、正確には多分違う。
そのローカル名前空間上で、最外殻に至るまでのローカル名前空間からその関数の実行に必要なシンボルをコピって辞書化したもの、みたいだ。

x = 1
def test():
    x, y = 2, 100
    def test():
        x, z = 3, 200
        print('b', x, y, z, locals())
    print('a', x, y, locals())
    test()
test()
a 2 100 {'test': <function test.<locals>.test at 0x10cd37400>, 'x': 2, 'y': 100}
b 3 100 200 {'z': 200, 'x': 3, 'y': 100}

「b」のlocals()の結果にyがあるので「ひぇ」ってなる。仮にそのローカル名前空間の名前と値のマッピングだけであればこれはあってはいけない。
関数をパースする段階で参照専用の名前yを見つけてこの辞書に突っ込んでいる。

Note The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

x = 1
def test():
    x, y = 2, 100
    def test():
        x, z = 3, 200
        print('b', x, y, z, locals())
        locals()['z'] = 300
        print('c', x, y, z, locals())
        locals()['y'] = 300
        print('d', x, y, z, locals())
    print('a', x, y, locals())
    test()
    print('e', x, y, locals())
test()
a 2 100 {'test': <function test.<locals>.test at 0x102fd7400>, 'x': 2, 'y': 100}
b 3 100 200 {'z': 200, 'x': 3, 'y': 100}
c 3 100 200 {'z': 200, 'x': 3, 'y': 100}
d 3 100 200 {'z': 200, 'x': 3, 'y': 100}
e 2 100 {'test': <function test.<locals>.test at 0x102fd7400>, 'x': 2, 'y': 100}

代入がガン無視されている。注意書きの通りだ。

当然、この挙動は exec() にだって影響が出る

Note The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.

def test():
    x = 0
    exec('x = 10', globals(), locals())
    print(x)

test()
0

正しいのは例えばこう

def test():
    x = 0
    exec_local = {'x': x}
    exec('x = 10', globals(), exec_local)
    x = exec_local['x']
    print(x)

test()
17
11
9

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
17
11