Dynamic variable creation from string

alex23 wuwei23 at gmail.com
Mon Dec 12 01:50:32 EST 2011


On Dec 12, 3:00 pm, Ethan Furman <et... at stoneleaf.us> wrote:
> For me, half of it is to avoid the typing, the other half to avoid the
> reading.  ;)

Believe me, I get that, I've been more than guilty of it in the
past :)

But the reading here is important. If I see a dictionary lookup, I
expect it to be accessing a dictionary; if I see an attribute
reference, it might be wrapped in a descriptor. (And yes, I'm very
much aware that ultimately an attribute lookup _is_ a dictionary
lookup, but it's everything else that potentially happens after that
point that is important here.) Changing the visual short circuits any
understandings; then again, I tend to hate pesudo/mini-DSLs for the
same reason... I can't just rely on my understanding of the language,
I need to understand a specific implementation and mentally flag
whether it's relevant or not.

I also don't understand the original desire to create dynamic
variables either. Either you know the names in advance, in which case
just set up the necessary scaffolding to inject them where you need
them, or you _don't_ and there's no value in creating them anyway
because you don't know how to refer to them in your code.

So if you know the names, use dictionary unpacking:

    userData = dict(a = 1, b = 2, c = 3)

    def func(a,b,c):
        return a + b + c

    >>> func(**userData)
    6

If the dictionary has more values than you need, catch & discard the
ones you don't want in **kwargs.



More information about the Python-list mailing list