setting variables in the local namespace

Chris Withers chris at simplistix.co.uk
Tue Oct 13 18:05:03 CEST 2009


Hi All,

Say I have a piece of code like this:

         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 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...

What I'd be looking for is something like:

locals()[name]=value

...or, say:

setattr(<somethingspecial>,name,value)

Now, I got horribly flamed for daring to be so heretical as to suggest 
this might be a desirable thing in #python, so I thought I'd ask here 
before trying to take this to python-dev or writing a PEP:

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

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

cheers,

Chris

-- 
Simplistix - Content Management, Batch Processing & Python Consulting
            - http://www.simplistix.co.uk



More information about the Python-list mailing list