Define a class which includes __iter__
, pass the object to function
def log(message, *values):
pass
favorites = [7, 33, 99]
log('Favorite colors', *favorites)
the sequence should be normal, positional, optional arguements
def decode(data, default=None):
"""Load JSON data from a string.
Args:
data: JSON data to decode.
default: Value to return if decoding fails.
Defaults to an empty dictionary.
"""
if default is None:
default = {}
Add *
before keyword arguments, then it becomes keyword-only
def safe_division_c(number, divisor, *,
ignore_overflow=False,
ignore_zero_division=False):
Avoid doing dictionary nesting more than one level
Use namedtuple
type
import collections
Grade = collections.namedtuple('Grade', ('score', 'weight'))
Use lambda
and closure
Function is first class object
class CountMissing(object):
def __init__(self):
self.added = 0
def __call__(self): # function
self.added += 1
return 0
counter = CountMissing() # counter is a function
result = defaultdict(couter, current)
Map reduce example. Add the creation funtion to the base class level
class InputData(object):
def read(self):
raise NotImplementedError
@classmethod
def generate_inputs(cls, config):
raise NotImplementedError
class Worker(object):
def map(self):
raise NotImplementedError
def reduce(self, other)
raise NotImplementedError
@classmethod
def create_workers(cls, input_class, config):
workers = []
for input_data in input_class.generate_inputs(config):
workers.append(cls(input_data)) #cls => the sub-class itself
# LineCountWorker, PathInputData are sub-classes
workers = LineCountWorker.create_workers(PathInputData, config)
Avoid the subclass override the previous subclass, super()
class only called once
class Goodway(TimeFive, PlusTwo):
def __init__(self, value):
super(Goodway, self).__init__(value)
# super().__init__(value) in python 3
ret = Goodway(5) # order is defined in MRO
- this makes python a good glue
- communicate() to run subproceses
- in python3, we could add timeout
- GIL, threading may causes program running longer !
- but if the call is IO bound, for example, system call, threading will
help
Decorators: run addional code before/after any calls
Use wraps
to make the function name unchanged
def trace(func):
@wraps(func)
def wrapper(*args, **kwargs):
pass
return wrapper
- with == try/finally block
- enalbe your objects to
with
usingcontextlib
- simpler than adding
__enter__
__exit__
@contextmanager
def debug_logging(level):
logger.setLevel(level)
try:
yield # which with block execute
# yield logger #if we wanna use as
finally:
pass
- pickle.dump and pickle.load useful for saving game
copyreg.pickle(GameState, pickle_game_state)
- stable import path
deque()
OrderedDict
defaultdict
heapq
,heappush
,heappop
- =bisect_left(x, 99999) binary serach
itertools