Thread: Static Python

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Posts
    81
    Rep Power
    12

    Static Python


    Hi. I am trying to create a class that will allow only one instance of itself to be created. I was looking for something like static(in c++) for python. Is there something like this? Thanks!
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    133
    Rep Power
    11
    Originally Posted by jimo9
    Hi. I am trying to create a class that will allow only one instance of itself to be created. I was looking for something like static(in c++) for python. Is there something like this? Thanks!
    What you want to do is to implement the Singleton pattern. You'll want to look at the Overriding the __new__ method section of Unifying types and classes. I've linked directly to the specific section where implementation is discussed but I recommend reading the entire essay.
    Last edited by percivall; April 20th, 2004 at 06:35 PM.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    There are several ways to create singletons in Python, and they are covered in depth in the Python Cookbook on ASPN.

    http://aspn.activestate.com/ASPN/Coo...n/Recipe/52558
    http://aspn.activestate.com/ASPN/Coo...n/Recipe/66531
    http://aspn.activestate.com/ASPN/Coo...n/Recipe/66531
    http://aspn.activestate.com/ASPN/Coo.../Recipe/102187

    Some of them use deep Python magic, such as metaclasses.

    However the simplest way to create a singleton is to just use a module instead of a class. It is not as powerful as a class singleton since you can't use inheritance, but 99% of the time you don't need to.

    I generally avoid singletons since they tend to increase coupling between classes and make unit testing harder.

    Dave - The Developers' Coach

IMN logo majestic logo threadwatch logo seochat tools logo