Python Number Conversion Chart
From | To | Expression |
---|
>>> 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)) |
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): |
"""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) |
From | To | Expression |
---|
def singleton(cls): | |
instances = {} | |
def getinstance(): | |
if cls not in instances: | |
instances[cls] = cls() | |
return instances[cls] | |
return getinstance |
>>> 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'] |
>>> 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'] |
>>> 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'), |
>>> 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'), |
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 |