C-style static variables in Python?

Mel mwilson at the-wire.com
Fri Apr 2 13:35:02 EDT 2010


kj wrote:

> In <mailman.1437.1270163476.23598.python-list at python.org> Steve Holden
> <steve at holdenweb.com> writes:
> 
>>But the real problem is that the OP is insisting on using purely
>>procedural Python when the problem is screaming for an object-oriented
>>answer.
> 
> My initial reaction to this comment was something like "What? switch
> from procedural to OO just to be able to do some one-time initialization
> of function-private data???"

Yeah, actually.  If the subject had been "Python-style object attributes in 
C?" somebody might have suggested C static variables.  An example I wrote 
lately

volatile static int random_bit ()
{
	static unsigned short lfsr = 0xACE1u;		// seeded LFSR 
	// taps: 16 14 13 11; characteristic polynomial: x^16 + x^14 + x^13 + 
x^11 + 1
	lfsr = (lfsr >> 1) ^ (-(lfsr & 1u) & 0xB400u);
	return lfsr & 1;
} // random_bit

(excuse is: this was written for cheap execution in an 8-bit processor.)

This does OK -- but fails the instant I decide that my program needs more 
than one pseudo-random bit stream.  Then I have the choice of writing 
several different random_bit functions, or extending random_bit to take a 
pointer to a seeded LFSR provided by the individual caller.

Refactoring the Python function to a Python class, as you mention later, 
solves the static-access problem, but that solution is just as vulnerable to 
the need-more-than-just-the-one problem as my C function.

	Mel.






More information about the Python-list mailing list