[Tutor] multiple assignments when reading a file

Sivaram Neelakantan nsivaram.net at gmail.com
Thu Jul 11 14:18:03 CEST 2013


Thanks for the detailed explanation below.  I've replied below.

On Thu, Jul 11 2013,Dave Angel wrote:

[snipped 19 lines]

> That's a pretty common question here.  And the right answer is "you
> don't want to, not really."
>
> The real question is what you mean by "var names."  If you mean you
> want the particular function you're in to have 217 extra locals, with
> names something like
>   field000, field001, ...  field216
>
> then you're just out of luck.  The names have to be known at the

Drat!  So nothing to promote laziness in me!


> function's compile time, so somewhere you have to type them all in, in
> some form of name-binding assignment.  The easiest one of those is 
> what you already described.
>     field000, field001, field002  <etc.> field216 = lines.split()
>
> There might even be a limit of how many locals a function may have,
> but I don't know what it is.  Probably at least 256.

Right, I'll keep that in mind.

>
> Next choice?  Make them all global?  that indeed can be faked, by
> manipulating the globals() dict.  The idea is abhorrent, however,
> since mutable globals are a wart on the landscape.
> 
> third choice?  Put them in a list.  Whaddya know, they already are.
> So just assign a name to that list.  Referencing them is now by
> subscript. And you can actually do slices and loops readily, which you
> can't easily do on "var names."

This seems the easiest but I already foresee hardcoded subscripts all
over the code which I will promptly forget the very next day of what
it stands for.

>
> Next choice?  Put them in a dict.  This works just like a list, except
> the subscript doesn't have to be continguous ints.

alright.

>
> Final choice?  Put them in a namespace.  Something like:
>
> class NewSpace:
>     pass
>
> data = NewSpace()
> for index, item in enumerate(lines.split()):
>     data.__dict__["x" + str(index)] = item
>

OO, I'd stay away till I get the basics right.


[snipped 19 lines]



 sivaram
 -- 



More information about the Tutor mailing list