Evil Python #1: Accessing the caller’s variables
There’s some pretty nasty* things you can do with Python, if you really try. Here’s one that I came across today on the testing-in-python list. Turns out you can programmatically access the call stack. Here’s an example:
>>> def foo(): ... name = "Kevin" ... bar() ... >>> foo() Hello, Kevin
You have to ask what kind of evil person would write such an unmaintainable piece of code. I found it sufficiently fascinating though, that I figured I’d share. If you ever decide to use something like this in production… well, I’ll leave that to you and your conscience.
>>> def bar(): ... print "Hello,", sys._getframe(1).f_locals['name']
* nasty: unmaintainable, confusing, unobvious.
Now this is something you can really call ‘nasty’.