[Tutor] Initialize values from a text input file

Alan Gauld alan.gauld at btinternet.com
Tue Jan 4 00:26:43 CET 2011


"Tim Johnson" <tim at johnsons-web.com> wrote

> consider the following console session:
>>>> L = ['foo','bar']
>>>> locals()[L[0]] = L[1]
>>>> foo
> 'bar'
>>>> locals()
> {'__builtins__': <module '__builtin__' (built-in)>, 'L': ['foo',
> 'bar'], '__package__': None, '__name__': '__main__', 'foo': 'bar',
> '__doc__': None}
> 
> I could initialize variables in a local scope, or I could build a
> dictionary. Actually the dictionary is preferable for the targeted
> application.

Except in extreme cases I'd say a dictionary was better in 
almost any situation. Messing with locals() is a dodgy business 
at best, and can lead to debugging insanity at worst, its better 
to keep externally initialized data explicit in almost every case.

> However, for the sake of edification, I would welcome comments on
> the session above, and let's pretend that `L' is the result of a
> line read from a file and split on '\t'.

My only comment: Don't go there... creating random variables 
in your namespace that don't actually appear in your code makes 
using global variables seem positively benign.

Once you create them what are you going to do? 
Litter your code with

try:
     doSomething(withNameThatMightExist)
except NameError:
     doSomethingElse()

It is a minefield just waiting to suck you in.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list