namespace/dictionary quandry

Peter Otten __peter__ at web.de
Sat Sep 18 04:54:41 EDT 2004


Jack Carter wrote:

> This will result in:
> 
>     >>> bosco=5
>     >>> if 1:
>     ...   attach bosco
>     ...   bosco=7
>     ...   attach bosco
>     ...
>     DoAttach: ['5']
>     DoAttach: ['5']    <--- WRONG (at least, not what I want)
>     >>> attach bosco
>     DoAttach: ['7']

The suite

attach bosco
bosco = 7
attach bosco

is only executed after the final empty line. Therefore any access to the
right dictionary in the process() method will give you the current value
bosco==5 which is not what you want.
You are in effect translating the suite into (simplified)

DoAttach(5)
bosco = 7
DoAttach(5) # the previous line has not yet been executed

I think the easiest way to get the desired effect ("late binding") is like
so:

def process(self, line):
    temp_line = line.lstrip()
    front_padding = line[:len(line)-len(temp_line)]

    match = self.regexp.match(temp_line)
    if match:
        line = front_padding + "myparse.DoAttach(bosco)"

    return line

I. e. change the generated line to contain variable names instead of values
and leave the resolution to python. (You hint you don't wont that either.
Why?)

By the way, I wasn't able to run your code - the indentation is seriously
messed up. I recommend you ensure a 4-space indentation in all code you
currently have before you move on. That will spare you a lot of trouble
later on.

Another minor issue: 'value is 0' may or may not work depending on the
python implementation ('value is 1000' won't work even in current CPython).
With 'value == 0' you are on the safe side.

Peter




More information about the Python-list mailing list