[Tutor] Fwd: What's in a name?

Steven D'Aprano steve at pearwood.info
Sat Jan 4 06:36:57 CET 2014


On Fri, Jan 03, 2014 at 01:55:29AM -0500, Keith Winston wrote:
[...]
> I want to iterate through a bunch of lists, subsequently printing both list
> members (via indexing, for example) and the name of the list I'm on.

Why? What does this gain you?

Now, it's true that when *debugging code*, being able to see the name of 
the variable and the contents of the variable is useful. But in ordinary 
code, why would you care to print the name of the variable and its 
contents. Who cares what the variable is named?

Debuggers stick all sorts of nasty hooks into the running interpreter in 
order to do this (and much more), and we should all be thankful that (1) 
debuggers exist, (2) that they aren't running by default, and most 
importantly (3) that we don't have to write code like them.

In addition to powerful debuggers, we also have fantastic poor-man's 
debugger called "print":

for name, value in zip(
            'alist blist clist'.split(), [alist, blist, clist]):
    print(name, "=", value)


Yes, it's a little bit messy code. We have to repeat the name of the 
variable twice. But this isn't code that will hang around in the 
finished program. It only need exist for just long enough to debug the 
problem we're having (you are having a problem, I presume?), then, it's 
job done, it's gone. (Be ruthless at deleting code that isn't pulling 
its weight.) And in the meantime, the rest of our code doesn't need to 
use any nasty indirect code, it can just use (say) alist.append(42) 
instead of eval('alist').append(42).

For longer-lasting indirect code, rather than use eval, its better to do 
something like this:

namespace = {
    'alist': [1, 2, 4, 8, 16, 32],
    'blist': ['fe', 'fi', 'fo', 'fum'],
    'clist': [1.5, 2.5, 3.5, 4.5, 5.5, 6.5]
    }

for name, value in namespace.items():
    print(name, "=", value)


eval is a nuclear-powered bulldozer. Don't use it for cracking nuts.


-- 
Steven


More information about the Tutor mailing list