[Tutor] What's in a name?

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


On Sat, Jan 04, 2014 at 12:32:19AM -0500, Keith Winston wrote:
> On Fri, Jan 3, 2014 at 11:59 PM, Steven D'Aprano <steve at pearwood.info>wrote:
> 
> > thelist = vars()[name]
>
> 
> I see: vars() certainly looks less dangerous than eval(), but I'm guessing
> that's still smelly code? I hadn't known about vars() or I probably would
> have used it.

Yes, it's still a bit smelly: but only a bit, since while "direct" code 
is the idea, sometimes the only way to do things is with one (or two) 
layers of indirection.

Code should (as a general rule) not rely on, or be affected by, the name 
of the variable. Functions which inspect the running environment (i.e. 
peek deep inside the interpreter) or use eval or other techniques to 
operate "behind the scenes" on *names* rather than values can often lead 
to confusing code. As debugging tools, they're useful. Putting such 
functionality inside normal everyday programs is a code smell.


-- 
Steven


More information about the Tutor mailing list