Class


23
Jul 10

Singleton pattern in Python

Just came up with a simple pattern for singletons in Python using a class decorator: def singleton(cls): instances = {} def instance(): if cls not in instances: instances[cls] = cls() return instances[cls] return instance Little demo: >>> @singleton ... class Foo(object): ... pass ... >>> f1 = Foo() >>> print id(f1) 3077430124 >>> f2 = [...]

22
Jul 10

Python ternary operator

Python has no ternary operator, or has it? At least not directly, we had a discussion about possible solutions in the #python IRC channel on FreeNode and after some filddling I came up with this hack abusing the Python slicing magic: class Ternary(object): ''' Ternary-ish emulation, it looks like C-style ternary operator:: x = a [...]