I suspect that you are misinterpreting this paragraph...
*Important warning:* The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:
The argument packet_counter will get set to 0 everytime the function gets call. If 0 happened to be an expression like [] (new list), then packet_counter would get set to that list object every funtion call.
You may want a global variable? def handle_packet.... global packet_counter = 0 ...
I think that may be OK - it's been a while since I played with Python
Brad
Andrew Errington wrote:
Okay, so I started playing with Python yesterday, and it's really cool.
I don't yet understand the variable scoping rules, but the problem I am currently grappling with is 'initial values in functions'.
For example, I am writing a program to decode packets from an incoming data stream, and I want a function that, once the packet has been accumulated, verifies the packet's integrity by checking the CRC. All the bit/byte/packet handling is done and working, and the CRC code works. All I want is a simple packet counter:
def handle_packet(new_packet, packet_counter=0, bad_CRC=0): packet_counter = packet_counter + 1
if calc_CRC(new_packet) != 0: bad_CRC = bad_CRC + 1 print "Bad CRC ", else: print "Good CRC",
print bad_CRC, "/", packet_counter
The point here is that the function definition contains the initial
values for the number of packets (packet_counter) and the number of
bad CRCs seen (bad_CRC). I expect the first call to initialise these
two variables to zero (once) and increment as appropriate in
subsequenct calls. As I said, it all works, but for a sequence of good packets I get
Good CRC 0 / 1 Good CRC 0 / 1 Good CRC 0 / 1 ...
Whereas I want
Good CRC 0 / 1 Good CRC 0 / 2 Good CRC 0 / 3 ...
I am using as my reference
http://python.active-venture.com/tut/node6.html#SECTION006600000000000000000
Section 4.7.1, and I am running Python 2.4.1.
It seems to me I got all the hard bits working, and this should be trivial...
Thanks in advance,
Andy
