#16 locals() and interpolation

open-works-for-me
nobody
None
5
2003-11-17
2003-11-06
Anonymous
No

Often when locals() is called (in my code), it is to
perform interpolation from local variables:

def f():
a = 1
b = 2
x = 3

s = 'a=%(a)d b=%(b)d' % locals()

It would be really nice to see that x is not used by
looking into the string. There will be times that is
not possible since the string being interpolated
(into?) will be a variable.

Perhaps the answer is to disable the 'unused local'
check when locals() has been called. Note the following:

def f():
a = 1
b = 2
return g(locals())

def g(map):
return 'a=%(a)d b=%(b)d' % map

For context, my code matches the first example. I'm
writing code that is building string messages for 3rd
parties who have each designed their own protocols.
Naturally most of them are difficult to automate, so I
end up with hardcoded strings and I interpolate the
message values for some variables into them. I prefer
using local variables to eliminate all the quotes when
using a local dictionary.

v['a'] = 1
v['b'] = 2
...

Discussion

  • Neal Norwitz
    Neal Norwitz
    2003-11-17

    Logged In: YES
    user_id=33168

    What version are you running? I just tested your code with
    2.2 and 2.3. Both versions produced the warning. This is
    with the version of pychecker in cvs, but I think the last
    release worked the same.

     
  • Neal Norwitz
    Neal Norwitz
    2003-11-17

    • status: open --> open-works-for-me