I should preface this by saying the following: I know this functionality is not supported by default - what I'm attempting is a hacky workaround that has very little practical application, and is a complete practice in mental masturbation as a result of boredom and curiosity. That said, I'm trying to do the following:
Based upon the following Python code,
with BuildFile('mybuild.build') as buildfile:
objdir = 'obj'
I'd like to generate a file, mybuild.build with the contents:
objdir = obj
Ideally, I'd want to associate the variable name at the point of creation, so that if I were to set a breakpoint just after the objdir = 'obj' I'd like to be able to do the following:
>>> print repr(objdir)
'objdir = obj'
That wouldn't be possible with builtin functionality, however, since there's no way to override the type inferred from the syntax. I may end up hacking together a workaround in the BuildFile.__enter__ method that uses ctypes to monkey patch the tp_new or tp_dict fields on the underlying PyTypeObject struct (and subsequently revert that override at exit), but for simplicity sake, let's just assume that I'm not associating the variable name until I reach the BuildFile.__exit__ method.
What I'm wondering about is the following:
Is there builtin Python functionality for halting execution, tracing back to the frame in which a local variable was declared, and getting the local name associated with a variable?
sys._getframe()does. You can even save the frame object for later and use it from outside of the frame (although usually at the cost of creating lots of circular references for the GC to clean up later). For example,[sys._getframe() for _ in range(1)][0].f_codelets you get at the hidden function inside CPython listcomps, and I can't think of any cleaner way to do it.