On Mon, 2010-10-04 at 16:14 -0400, Kamil Paral wrote:
----- "James Laska" <jlaska(a)redhat.com> wrote:
> > + def _convert_list_variables(self):
> > + '''
> > + We allow some variables to be as lists. We now need them as
> strings,
> > + so let's just join them with newlines.
> > + '''
> > + for var in ('self.highlights', 'self.outputs'):
> > + exec(r'if isinstance(%(var)s, list): %(var)s =
> "\n".join(%(var)s)' % {'var': var})
> > +
>
> Is 'exec' needed? I'm accustomed to 'exec' being generally bad
> thing,
> but I could be wrong. There probably is a reason, but why not
> something
> like the following instead of 'exec()' ...
>
> if isinstance(var, list):
> var = "\n".join(var)
>
The reason is that I wanted to be smart ^^ and not repeat exactly
the same code several times for different variables. Generally it
is highly problematic to change immutable variables in a loop, as
I consulted with jskladan. One way is to repeat the code for every
variable (i.e. no loop):
if isinstance(self.outputs, list):
self.outputs = '\n'.join(self.outputs)
if isinstance(self.highlights, list):
self.highlights = '\n'.join(self.highlights)
Second way is to use the exec above (then you have just the just
once and all variables listed just once).
for var in ('self.highlights', 'self.outputs'):
exec(r'if isinstance(%(var)s, list): %(var)s = "\n".join(%(var)s)'
% {'var': var})
Third way is something like this:
helper = [self.highlights, self.outputs]
for i in range(len(helper)):
if isinstance(helper[i], list):
helper[i] = '\n'.join(helper[i])
self.highlights, self.outputs = helper
Now you have one code, but several mentions of the variables.
You can imagine that some variables may be added, or renamed,
and less code and less variable names usage means less bugs.
For 10 variables, you wouldn't really use the first way. For
2 variables though... yeah, it's overkill.
We can do it any way that you deem appropriate, I won't feel
offended :) There seems to be no "clean" way in Python to do
this, unfortunately.
I wouldn't refer to me as the authority on what not to do in python! :)
It was just helpful to understand the different approaches.
For readability (and until we have more variables), I support
the first way now.
Aha, thanks for the details. That makes a lot of sense now. Yeah, I
recall now a similar example of changing loop arguments while in the
loop (see
http://qa-rockstar.livejournal.com/9530.html).
I leave it up to you on how to proceed.
Thanks,
James