Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Pythonのlocals()

More than 3 years have passed since last update.

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

環境は下記の通り (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を見つけてこの辞書に突っ込んでいる。

https://docs.python.org/3/library/functions.html#locals

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() にだって影響が出る

https://docs.python.org/3/library/functions.html#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()
amedama
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away