r/Python • • Nov 14 '17

Senior Python Programmers, what tricks do you want to impart to us young guns?

Like basic looping, performance improvement, etc.

1.3k Upvotes

629 comments sorted by

View all comments

Show parent comments

5

u/peedubyaeff Nov 14 '17 edited Nov 14 '17

Turns out the locals are stored in 'cells', and referenced in the bytecode: https://docs.python.org/2/c-api/cell.html

In [56]: def layer(params):
   ....:     def f(x):
   ....:         print params, x
   ....:     return f
   ....:

In [57]: foo = layer('these are my params')

In [58]: foo.__closure__[0]
Out[58]: <cell at 0x7fac61825830: str object at 0x7fac6186bc70>

In [59]: foo.__closure__[0].cell_contents
Out[59]: 'these are my params'

I don't see how you'd tie the cell back to the variable name though, so if you have more than one and need to know which is which you might be out of luck.

Edit - Of course, if you're actually using a debugger it will know the variable name from the frame you're in:

In [1]: import ipdb

In [2]: def layer(params):
   ...:     def f(x):
   ...:         print params, x
   ...:         ipdb.set_trace()
   ...:     return f
   ...:

In [3]: foo = layer('params')

In [4]: foo('x')
params x
--Return--
None
> <ipython-input-2-80f4294737a0>(4)f()
      3         print params, x
----> 4         ipdb.set_trace()
      5     return f

ipdb> params
'params'