0

One thing always confuses me, which is the counterintuitive dynamic / early binding of Python, especially when I have a for loop. I heard that Cython has some C language-style semantics, so I tried the following code, but I found that it is still dynamically / early bound

import cython


fns: list = []

i: cython.int

for i in range(100):
    fns.append(lambda: i)

print(fns[0]())
print(fns[1]())

output was

99
99

Can you achieve early-binding through Cython?

init 1
  • 39
  • 6
  • You should just handle this the way you would always handle this (in Python or the many other similar languages with static scope): use a factory function – juanpa.arrivillaga Mar 27 '23 at 02:11
  • 1
    I'm not sure why you though"c-like semantics" would matter. C doesn't have closures, as far as I am aware, so it doesn't have any semantics that would apply here – juanpa.arrivillaga Mar 27 '23 at 02:13
  • Does this kind of definition work in `cython`: `[lambda i=i: i for i in range(5)]` – hpaulj Mar 27 '23 at 03:31
  • @hpaulj even if it doesn't, that is IMO an ugly hack (although it has become an idiom). The principled solution is `def make_function(i): return lambda i` then in th loop, `[make_function(i) for i in range(5)]` – juanpa.arrivillaga Mar 29 '23 at 22:54

0 Answers0