Skip to content

Instantly share code, notes, and snippets.

@Nurdok
Nurdok / singleton_type.py
Created April 26, 2012 15:08
Singleton Implementation in Python Using Metaclasses
class SingletonType(type):
def __call__(cls, *args, **kwargs):
try:
return cls.__instance
except AttributeError:
cls.__instance = super(SingletonType, cls).__call__(*args, **kwargs)
return cls.__instance
@Nurdok
Nurdok / doubleiter.py
Created July 13, 2012 22:31
Double Iteration in List Comprehension
>>> seq_x = [1, 2, 3, 4]
>>> seq_y = 'abc'
>>> [(x,y) for x in seq_x for y in seq_y]
1: [(1, 'a'),
(1, 'b'),
(1, 'c'),
(2, 'a'),
(2, 'b'),
(2, 'c'),
(3, 'a'),
@Nurdok
Nurdok / doubleiter2.py
Created July 13, 2012 23:10
Double Iteration in List Comprehension
>>> result = []
... for x in seq_x:
... for y in seq_y:
... result.append((x,y))
>>> result
2: [(1, 'a'),
(1, 'b'),
(1, 'c'),
(2, 'a'),
(2, 'b'),
@Nurdok
Nurdok / doubleiter3.py
Created July 13, 2012 23:20
Double Iteration in List Comprehension
>>> seq = ['abc', 'def', 'g', 'hi']
... [y for x in seq if len(seq) > 1 for y in x if y != 'e']
['a', 'b', 'c', 'd', 'f', 'g', 'h', 'i']
@Nurdok
Nurdok / doubleiter4.py
Created July 13, 2012 23:25
Double Iteration in List Comprehension
>>> result = []
... for x in seq:
... if len(seq) > 1:
... for y in x:
... if y != 'e':
... result.append(y)
... result
['a', 'b', 'c', 'd', 'f', 'g', 'h', 'i']
@Nurdok
Nurdok / decorator.py
Created July 14, 2012 15:16
Singleton Blog Post
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@Nurdok
Nurdok / python_conversion.md
Last active July 11, 2024 15:00
Python Conversion

Python Number Conversion Chart

From To Expression
"""TODO: A docstring"""
class Bean(type):
def __init__(cls, name, bases, dct):
def init(self, *args, **kwargs):
for attr, arg in zip(cls._attrs, args):
setattr(self, attr, arg)
for name, value in kwargs.iteritems():
setattr(self, name, value)
def withenv(name):
def inenv(func):
def new_func(*args, **kwargs):
print 'withenv {}'.format(name)
func(*args, **kwargs)
return new_func
return inenv
def withenv_byname(func):
def new_func(self, *args, **kwargs):
>>> class Works(object):
... a = 1
... b = [a + x for x in range(10)]
>>> Works.a
0: 1
>>> Works.b
1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> class DoesntWork(object):
... a = 1
... b = (a + x for x in range(10))