On Jul 11, 2008, at 8:04 AM, Stefan Behnel wrote:

> Hi,
>
> Robert Bradshaw wrote:
>> This is in fact very much in line with how closures would be
>> implemented--there would be an extension class that would hold the  
>> state
>> (and garbage collection would happen when this object went out of  
>> scope,
>> so no issues for generators or closures).
>
> Just coming up with a couple of corner cases to make sure they will  
> work in
> this solution. Could you comment on how they are handled?
>
> 1)
>
> def f():
>     x = 1
>     def a(): print x
>     def b(): print x
>     return (a,b)

There will be a cdef class created for a and b, as well as one  
representing the scope of f, with a __call__ method containing the  
body of the function. The def a() and def b() lines would instantiate  
this class and assign them to local variable a and b (which have a  
reference to the containing scope). When both of these are collected,  
the scope will be as well.

> 2)
>
> for i in range(10):
>     def a(): print i
>     a()
>
> (outputs 0-9 in Python)

This isn't an inner function at all. To fix the scoping rules, "def"  
would create a function at the top level, and then do an assignment  
to the variable "a."

> 3)
>
> for i in range(10):
>     if i == 0:
>         def a(): print i
>     a()
>
> (outputs 0-9 in Python)

Exactly the same as (2). There is nothing special about the scoping  
here, it's "outer" scope is the module scope, just as in the standard  
def function. The reason Cython has this restriction is that  
functions can only be created once.

- Robert

_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to