Oddity question

mcherm mcherm at destiny.com
Tue Feb 26 16:04:15 EST 2002


> I was fooling around with sockets last night, using a thread to deal =
> with the read part and another method to do the print.
> 
> like this:
> 
> def thread_read (self):
>   while 1:
>     self.buf=3Dself.buf+self.my_socket.recv (8)
> 
> def print_buf(self):
>   if buf:
>     print "bufeer-->",buf
>     buf=3D'""
> 
> But, what happened to me was that the -buf =3D ""- line seemed to be not =
> working     [...]

> So, I dont know why I changed thread_read function to:
> 
>   while 1:
>     aux=3Dself.my_socket.recv (8)
>     self.buf=3Dself.buf+aux
> 
> And this version worked properly..... but I still do not know why.

Well, I can't tell exactly what you were doing here (try sending plain 
text instead of html... it doesn't get mangled as much), but I do see 
one thing. In the example that doesn't work you have a line 'buf=""' at 
the end of a function or method, while the example that DOES work has 
'self.buf=self.buf+aux' inside a loop.

If buf is a local variable, then 'buf=""' at the end of a function will 
only modify the local variable and do nothing to the actual buffer 
(strings are immutable in Python). Modifying self.buf in a loop will not 
be lost in this fashion.

Does that help any?

-- Michael Chermside








More information about the Python-list mailing list