# Python: Generator Expressions / joblib.Parallel

Yao Yao on March 22, 2018

Generator expressions are syntactic sugar: they can always be replaced by generator functions, but sometimes are more convenient.

Syntax Tip: When a generator expression is passed as the single argument to a function or constructor, you don’t need to write its parentheses.

## 1. Generator Expression and Parentheses

Initially generator expressions always had to be written inside parentheses, as documented in PEP 289. The additional parenthesis could be omitted on calls with only one argument, because in this case the generator expression already is written inside parentheses.

• 这个函数其实只有一个参数
• 这个参数其实是个 generator
• 不要想到 unpack 那边去了
# For instance, the following summation code will build a full list of squares in memory, iterate over those values, and, when the reference is no longer needed, delete the list:
sum([x*x for x in range(10)])  # OK

# Memory is conserved by using a generator expression instead:
sum(x*x for x in range(10))  # OK


>>> tuple(i for i in [1, 2, 3])
(1, 2, 3)


## 2. SyntaxError: Generator expression must be parenthesized

sum([x for x in range(10)], default = 0)  # OK

sum(x for x in range(10), default = 0)  # SyntaxError


## 3. joblib.Parallel

joblib.Parallel 里的一个用法是：

scores = parallel(
delayed(_fit_and_score)(
clone(estimator), X, y, scorers, train, test, verbose, None,
fit_params, return_train_score=return_train_score,
return_times=True, return_estimator=True, error_score=-1)
for train, test in cv.split(X, y, groups))


def delayed(func)(*args, **kwargs):
return func, args, kwargs


def gen():
for train, test in cv.split():
yield func, args, kwargs