29 Kasım 2008 Cumartesi

Singleton Pattern in Python

The Singleton actually is not something very different or new invention. The purpose of it is to have only a single instance of some class so you can have a global point of access which is cool. For now i think i can use it for configuration manager classes, some cool loggers and some context variables. Maybe i will find more of em. The Singleton pattern is a little bit different from one that is in Java. In Java to make a singleton you have to make your constructor private and have some static method to do the instance initialization. In python what you have todo is override the __new__ method of the Singleton candidate. There are lots of examples on the net related with that topic so you can search one before use mine. Actually mine is not written or thought by me i found it also (from aspn CookBook site) :)

Here is the first version i found and think is good : LINK
As you will see there is some time and sleep things in it , i put em there to test what happens when some threaded classes use it. And as you may imagine some of the threads got different references of that Class. Here is the Thread i used :

from threading import *
import time
import thread

class ThreadSingleton(Thread):
A simple thread to work on that
def __init__(self,id):
self.id = id

def run(self):
Here initialize the singleton

print "Im thread %d and %d"%(self.id,id(self.s))

def get_singleton(self):
return id(self.s)

Here is the code that tests it :

def singleton(t="threaded"):
for j in range(100):
threads = []
for i in range(10):
if t!="threaded":

for i in threads:

for i in threads:

print "The final ids are :"
t0 = threads[0]

for i in threads:
assert t0.get_singleton() == i.get_singleton()


if j%10 == 0:
print "************** %d COMPLETED **********"%j

After those tests i got some Assertion Errors because some of the threads got different references of the object. What we know from here is that our Singleton is not thread-safe and we should fix it. Here is the threaded version of the Singleton LINK :

To test that new verison i nedded some new ThreadClass to call the new created Singleton :

class RealThreadedSingleton(ThreadSingleton):

def run(self):
Here initialize the singleton

print "Im thread %d and %d"%(self.id,id(self.s))

After final changes i run the tests 1000 times and didnt have any problems. Why we should bother to have Singleton threa-safe , because i'm going to use it in some frameworks that uses threads heavily, so icant be sure when that one will be called. To conclude, when write some cool classes always should think the posibility of theraded usages.

28 Kasım 2008 Cuma

Decorator Pattern in Python

Our next step in DP is Decorator pattern, as u know Python also has some decorator options you can apply to your programs by @ sign. But if you want to apply decoration to classes in object level you have to change the stuff a little bit. I always thought that Java's IO library is very confusing, you create a FileInput class then you put it in a BufferReader and etc. When i read the Decorator chapter in Head First i realized that the Java IO API is using that pattern there. Well why do you need decorator pattern? Lets go from IO API example :
1. You have a normal reader
2. You need a reader that converts the input to lowercase, so what you do is create a new UpperReader
3. You need now a reader that converts input to a sha1 sum , what you do is create a Sha1Reader
4. You need a reader that converts input to uppercase sha1sum , what you do is create a Sha1UpperReader
5. The 4. item can be removed if you used the decorator pattern

Shortly, decorator pattern wraps an object and change its flow before or after the target operation. For the example above you can change the incoming input or process it to sth else.

Here is the implementation i wrote in Python and put on my personal github repo : LINK

A sample usage of above can be like that :

  1. def deco():

  2. from pyalgorithm.dp.decorator import *

  3. print "The normal file reader content"

  4. n = NormalFileReader("some.txt")

  5. print n.read_content()

  6. print "Sha1 sum of the read info"

  7. sh =DecoratoSha1Reader(

  8. NormalFileReader("some.txt")

  9. )

  10. print sh.read_content()

  11. print "Sha1 sum but with upper cases"

  12. up = DecoratoUpperFileReader(

  13. DecoratoSha1Reader(

  14. NormalFileReader("some.txt")

  15. )

  16. )

  17. print up.read_content()

The output is sth like that:

The normal file reader content
Hey im the content!!!

Sha1 sum of the read info
Sha1 sum but with upper cases

Well, it is the end of the today's pattern "decorator man". The post will be a good reference for me when forget the things :)

25 Kasım 2008 Salı

Observer Pattern in Python

Well here are the first things i got from "Head First Design Patterns" book :) I was working on a big web project and have also some small open source projects i try to finish. I stoppped codding on that projects immediately after read the first chapter of the book :) I realized that have big gaps in my programming skills about patterns. What i know now is :

- Knowing OO principles and rules doesnt make u a OO guru.
- Inheritance is not the best way of code reuse.
- Inherit the static parts and use composition for things that can change in the future.
- Less dependency between classes is alway better.

Will add to those more in the future i think.
Ok lets go back to the title of that entry. Sometimes we need to send some notifications to other classes from a specific class. What i would do before knowing the observer pattern would be sth like that. I would define a notifier() method and will call the classes i want to notify :

  1. def notify(self):

  2.    classA.update(args)

  3.    classB.update(args)

  4.    classC.update(args)


Ok it seems good for now but wat happens if you want to notify the classes D and E in the future u have to add them to the list above. That means altering the existing code which may not be a good idea. Ok now the classB doesnt want anymore to be notified , so what happens now ? It is very clear that the structure above is not the best for that situation. What we need is a dynamic srtucture which will allow us to add and remove new observers during the runtime without altering the existing code, so that is where the observer pattern comes into the scene ...

Here is the code i wrote to make a simple scenarion for observer pattern on my personal git_repo : LINK
Now we can do sth like that easily :

from pyalgorithm.dp.observer import *

print "I creatte the our subject"

c_s = ConcreteSubject()

c_s.my_x = 22

c_s.my_y =33

print "I notify my subscribers :"

c_s.values_changed() #that can be done dynamic but it is cool for now

print "Lets add a new XObserver"

x_o = ObserverX()

g_o = ObserverGeneral()


print "I notify my subscribers :"

c_s.values_changed() #that can be done dynamic but it is cool for now

print "Lets add a new GeneralObserver"


print "I notify my subscribers :"

c_s.values_changed() #that can be done dynamic but it is cool for now

print "The X observer doesnt want to know anything about us remove him"


print "I notify my subscribers :"

c_s.values_changed() #that can be done dynamic but it is cool for now

The output for that will be as follow :

I creatte the our subject
I notify my subscribers :
Lets add a new XObserver
I notify my subscribers :
Im X observer and got : 22
Lets add a new GeneralObserver
I notify my subscribers :
Im X observer and got : 22
I got all of them Here is my values 22 and 33
The X observer doesnt want to know anything about us remove him
I notify my subscribers :
I got all of them Here is my values 22 and 33

Well i think it became pretty dynamic ,i have lots of ideas where i can use that pattern. As a conclusion what i can say is that "Head First Design patterns" book is changing my vision to OO programming.


20 Kasım 2008 Perşembe

Got My Amazon Books

Really excited, i just got my amazon orders two great books. I hope to be better programmer now with those pearls :) The books arrived two weeks later from the estimated date but who cares i got em. One of them is about design patterns and other is about algorithms and programming. Here are the title's of books :

1.Programming Pearls
2. Head First Design Patterns

After finish em will write my reviews :)