'Borg' and multiple threads.

Reedick, Andrew jr9445 at ATT.COM
Wed Jan 9 10:02:13 EST 2008



> -----Original Message-----
> From: python-list-bounces+jr9445=att.com at python.org [mailto:python-
> list-bounces+jr9445=att.com at python.org] On Behalf Of Tobiah
> Sent: Monday, January 07, 2008 5:24 PM
> To: python-list at python.org
> Subject: 'Borg' and multiple threads.
> 
> I have a class that I call Borg that starts like this:
> 
> class Borg(dict):
> 
>         static_state = {}
>         def __init__(self):
>                 self.__dict__ = self.static_state
> 
> 
> 
> My question is why this seems to work.  I had the idea that
> there was a class object that is created when the file containing
> the definition is read, which actually contains the static
> information that is later accessed by instances.  Isn't this
> done when the cherrypy app first loads, rather than each time
> a browser hits the app?  Otherwise, where is the individual data
> stored for each of two simultaneous hits of the web page?
> 


I had a similar question except mine was from a bug.  (Thinking in c++
lead me to inadvertently create static class vars.)  

You can "print self" and use the id() function to get the memory
addresses of the variables and see what's going on.  In the code below,
mem4 is equivalent to your static_state.

count = 1

class Foo:

	mem4 = {}
	mem5 = {}

	def __init__(self):
		self.mem = {}

		global count
		count += 1
		self.mem2 = count

		self.mem3 = "%x" % (id(self))

		self.mem5 = {}

		print 'init count =', count


	def me(self):
		print "object:  ", self
		print "\tid(self.mem)  %x" % (id(self.mem)), " self.mem
=", self.mem
		print "\tid(self.mem2) %x" % (id(self.mem2)), "
self.mem2 =", self.mem2
		print "\tid(self.mem3) %x" % (id(self.mem3)), "
self.mem3 =", self.mem3
		print "\tid(self.mem4) %x" % (id(self.mem4)), "
self.mem4 =", self.mem4
		print "\tid(self.mem5) %x" % (id(self.mem5)), "
self.mem5 =", self.mem5
		global count
		count += 1
		print '\tcount =', count
		self.mem4[count] = count
		print "\tid(self.mem4) %x" % (id(self.mem4)), "
self.mem4 =", self.mem4
		#self.mem += count
		#print "\tid(self.mem)  %x" % (id(self.mem)), " self.mem
=", self.mem
		print


a = Foo()
b = Foo()
c = Foo()

a.me()
b.me()
c.me()



More information about the Python-list mailing list