setting variables in the local namespace

Mick Krippendorf mad.mick at gmx.de
Tue Oct 13 12:39:06 EDT 2009


Hello.

Chris Withers schrieb:
>         mname = model.__name__
>         fname = mname+'_order'
>         value = request.GET.get('order')
>         if value:
>             request.session[fname]=value
>         else:
>             value = request.session.get(
>                 fname,
>                 model.default_name
>                 )
> 
> Now, if I want to do *exactly* the same thing with a variable named
> 'sort', 

I don't really understand what you mean by "*exactly* the same".
    request.GET.get('sort') ?
or
    request.session[fname] = locals()['sort']
maybe? or sth else?

> I have to copy and paste the above code or do something hacky
> like have a dict called "vars" and manipulate that, or factor the above
> into a function and take the hit on the extra function call...

>From the "request.session" stuff I conclude you're writing a webapp.
Compared to all the other time consuming things involved, I think,
another function call is negligible.

> What I'd be looking for is something like:
> 
> locals()[name]=value

That will probably do what you want, and if that is a good idea depends
not on the pythonicity of it per se, but on the context in which you use
it, which I, as mentioned earlier, don't quite understand.

> - what is so wrong with wanting to set a variable in the local namespace
> based on a name stored in a variable?

What's your use case, I ask?

> - have I missed something that lets me do this already?

Yes, and, uh, yes. "locals()['foo'] = bar" works in that it does the
same thing as "foo = bar". So why don't you write that instead?

Mick.



More information about the Python-list mailing list