Javascript’s generator function needs an extra asterisk, but Python doesn’t need an extra identifier. Why is it designed like this?

  javascript, python

A Javascript generator function looks like this:

function *gen(n) {
  for (let i = 0; i < n; i++) {
    yield i;
  }
}
[...gen(10)]
// <- (10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Javascript needs to add an asterisk when declaring. If there is no asterisk, it will be reported.SyntaxError.

A python generator function looks like this:

def gen(n):
 for i in range(n):
 yield i
 
 >>> list(gen(10))
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Python does not need an extra identifier when declaring. Direct useYieldJust do it.

Both languages are usedYieldKey words, working principle is almost the same, even Javascript is copied python. Then why should Javascript add an asterisk instead? What is the meaning of this asterisk? Why is it designed like this? Is Javascipt too special or python too special?

I believe there should be a reason for this, after all, the process of ES2015 is quite harmonious (literally)

https://stackoverflow.com/que …


At last, I am free to perfect the answer.

One principle ES has been sticking to isCompletelyAvoid breaking changes, after all, the user’s browser version is not something programmers can interfere with. If the upgrade of users causes the old codes of some websites to fail, the organizing committee will definitely be sprayed to death. This is very different from other languages. Therefore, Compatibility is the primary reason. The new version of ES must be fully compatible with the old version of ES.

Readability and Generality are actually added effects. Generality is actually a pseudo requirement. Empty generators can be replaced by generators with 0 or 1 yield statement, and the latter is more readable than the former. Readability of ES is indeed better than Python’s. At least I can know whether it is a Generator or a Normal Function by reading only Header, but the advantage is only obvious when reading long code. These alone are not enough for dispython’s design.

As for why Python was used thendefIn fact, there is not much “meaning” but Guido’s intuition:-)PEP 255)。