Friday, September 14, 2007

How to Confuse _ and locals()["_[1]"]

So, after posting about the exception raising list comprehensions, I got this:
Kevin has left a new comment on your post "How to Add Memory Leaks to Python":

Doesn't '_' only exist in the interactive interpreter?
Kevin has a misunderstanding here in that there is a huge difference between the expressions _ and the locals()["_[1]"]. You might spot why they are so different, or you might not. The second, the one from the list comprehension, is unable to be accessed by name directly. You can only get at it via the locals() and globals() functions, depending on your scope (locals() always works right after the LC in question, though). The name is intentially something that, if tried to resolve as an actual name in the scope, won't find the object in question. Python will look for _ and then do a subscript lookup on key 1 on it. This is completely different than actually looking up the name _[1] in the dictionary where names are stored and grabbing up the value its bound to.

So, Kevin, your question can be answered in that its irrelevant, because we aren't dealing with _ at all. Also, open your profile so I can respond to you directly, next time.

1 comment:

Kevin Dangoor said...

Hey, thanks for the clarification.

I had actually tried it by taking your program and running it through Python directly. I made the mistake of not putting a try: except: around that, so it never got to my print globals()['_[1]'] statement. Oops!

I should've realized that the ['_[1]'] was just an ordinary dictionary lookup and not something weird and magical (though this key's existence is a little weird and magical!)

There are actually quite a few unexpected ways in which Python programs can leak memory. Thanks for bringing up one more!

I write here about programming, how to program better, things I think are neat and are related to programming. I might write other things at my personal website.

I am happily employed by the excellent Caktus Group, located in beautiful and friendly Carrboro, NC, where I work with Python, Django, and Javascript.

Blog Archive