# Pythonのlocals()

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

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

`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があるので「ひぇ」ってなる。仮にそのローカル名前空間の名前と値のマッピングだけであればこれはあってはいけない。

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}
```

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()
```