2

I am trying to make a toy singleton in python to learn the ins and outs of the language and am running into a problem with how python works. I declare the class like this

class ErrorLogger:
  # Singleton that provides logging to a file  
  instance = None

  def getInstance():
    # Our singleton "constructor"
    if instance is None :
      print "foo"

when I call it with

log = ErrorLogger.getInstance()

I get

 File "/home/paul/projects/peachpit/src/ErrorLogger.py", line 7, in getInstance
    if instance is None :
 UnboundLocalError: local variable 'instance' referenced before assignment

What is going on here, shouldn't instance be statically assigned Null? What would be the right way to do this?

dakillakan
  • 240
  • 2
  • 9
  • You can use `@staticmethod` or `@clsmethod`, both of which are described very well here: http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python – SimonT Apr 22 '14 at 04:00

1 Answers1

5

You have to call it with ErrorLogger prefix as it is a static variable.

class ErrorLogger:
  # Singleton that provides logging to a file  
  instance = None

  @staticmethod
  def getInstance():
    # Our singleton "constructor"
    if ErrorLogger.instance is None :
      print "foo"
Trein
  • 3,658
  • 27
  • 36
  • You can also use @classmethod, the differences are subtle but still there. – fr1tz Apr 22 '14 at 04:12
  • An advantage of `@classmethod` is that you'd get the class as an argument to the method, so you could use it to grab the singleton directly: `@classmethod def getInstance(cls): if cls.instanece is None: ...` – Blckknght Apr 22 '14 at 04:16