Skip to content

Instantly share code, notes, and snippets.

View python_class_closure
>>> 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))
View withenv_byname.py
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):
View pybean.py
"""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)
View python_conversion.md

Python Number Conversion Chart

From To Expression
@Nurdok
Nurdok / decorator.py
Created Jul 14, 2012
Singleton Blog Post
View decorator.py
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@Nurdok
Nurdok / doubleiter4.py
Created Jul 13, 2012
Double Iteration in List Comprehension
View doubleiter4.py
>>> 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 / doubleiter3.py
Created Jul 13, 2012
Double Iteration in List Comprehension
View doubleiter3.py
>>> 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 / doubleiter2.py
Created Jul 13, 2012
Double Iteration in List Comprehension
View doubleiter2.py
>>> 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 / doubleiter.py
Created Jul 13, 2012
Double Iteration in List Comprehension
View doubleiter.py
>>> 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 / singleton_type.py
Created Apr 26, 2012
Singleton Implementation in Python Using Metaclasses
View singleton_type.py
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
You can’t perform that action at this time.