dynamic assigments

Carl Banks pavlovevidence at gmail.com
Fri Mar 25 15:30:56 EDT 2011


On Mar 25, 5:29 am, Seldon <sel... at katamail.it> wrote:
> I thought to refactor the code in a more declarative way, like
>
> assignment_list = (
> ('var1', value1),
> ('var2', value2),
> .. ,
> )
>
> for (variable, value) in assignment_list:
>         locals()[variable] = func(arg=value, *args)

Someday we'll get through a thread like this without anyone mistakenly
suggesting the use of locals() for this....


> My question is: what's possibly wrong with respect to this approach ?

I'll answer this question assuming you meant, "hypothetically, if it
actually worked".

The thing that's wrong with your "declarative way" is that it adds
nothing except obscurity.  Just do this:

var1 = value2
var2 = value2

What you're trying to do is akin to writing poetry, or a sociological
research paper.  The emphasis in that kind of writing is not on clear
communication of ideas, but on evoking some emotion with the form of
the words (almost always at the expense of clear communication).

Same thing with your "declarative way".  It adds nothing to the code
apart from a feeling of formalism.  It doesn't save you any work: you
still have to type out all the variables and values.  It doesn't save
you from repeating yourself.  It doesn't minimize the possibility of
typos or errors; quite the opposite.  It DOES make your code a lot
harder to read.

So stick with regular assignments.


"But wait," you say, "what if I don't know the variable names?"


Well, if you don't know the variable names, how can you write a
function that uses those names as local variables?


"Er, well I can access them with locals() still."


You should be using a dictionary, then.

I have found that whenever I thought I wanted to dynamically assign
local variables, it turned out I also wanted to access them
dynamically, too.  Therefore, I would say that any urge to do this
should always be treated as a red flag that you should be using a
dictionary.


"Ok, but say I do know what the variables are, but for some reason I'm
being passed a huge list of these key,value pairs, and my code
consists of lots and lots of formulas and with lots of these
variables, so it'd be unwieldy to access them through a dictionary or
as object attributes, not to mention a lot slower."


Ah, now we're getting somewhere.  This is the main use case for
dynamically binding local variables in Python, IMO.  You're getting a
big list of variables via some dynamic mechanism, you know what the
variables are, and you want to operate on them as locals, but you also
want to avoid boilerplate of binding all of them explicitly.

Not a common use case, but it happens.  (I've faced it several times,
but the things I work on make it more common for me.  I bit the bullet
and wrote out the boilerplate.)


Carl Banks



More information about the Python-list mailing list