strange behavior in python

Posted by fsm on Stack Overflow See other posts from Stack Overflow or by fsm
Published on 2010-04-04T20:53:33Z Indexed on 2010/04/04 21:13 UTC
Read the original article Hit count: 341

Filed under:
|
|

The tags might not be accurate since I am not sure where the problem is.

I have a module where I am trying to read some data from a socket, and write the results into a file (append) It looks something like this, (only relevant parts included)

if __name__ == "__main__":
    <some init code>
    for line in file:
        t = Thread(target=foo, args=(line,))
        t.start()
    while nThreads > 0: 
        time.sleep(1)

Here are the other modules,

def foo(text):
    global countLock, nThreads
    countLock.acquire()
    nThreads += 1
    countLock.release()

    """connect to socket, send data, read response"""
    writeResults(text, result)

    countLock.acquire()
    nThreads -= 1
    countLock.release()

def writeResults(text, result):
    """acquire file lock"""
    """append to file"""
    """release file lock"""

Now here's the problem. Initially, I had a typo in the function 'foo', where I was passing the variable 'line' to writeResults instead of 'text'. 'line' is not defined in the function foo, it's defined in the main block, so I should have seen an error, but instead, it worked fine, except that the data was appended to the file multiple times, instead of being written just once, which is the required behavior, which I got when I fixed the typo.

My question is,

1) Why didn't I get an error?

2) Why was the writeResults function being called multiple times?

© Stack Overflow or respective owner

Related posts about python

Related posts about namespaces