RE: Function once: concern
"Mark Hahn" <[email protected]>
| Newsgroups | gmane.comp.lang.prothon.user |
|---|---|
| Message-ID | <000201c4691b$f5b1cc00$0b01a8c0@mark> |
Lenard Lindstrom wrote:
> A while back it was decided to use the anon, by convension,
> for declaring anonymous function. As such it is just a
> throw-away name. But this causes a problem for anonymous
> functions with a once: section. Take this example:
>
> handlers = {}
>
> def anon(): # Version 1
> once:
> anon.const = 1
> print(anon.const)
> handlers[1] = anon
>
> def anon(): # Version 2
> once:
> anon.const = 2
> print(anon.const)
> handlers[2] = anon
>
> handlers[1]() # Prints "1"
> handlers[2]() # Prints "2"
> handlers[1]() # Intend to print "1"; will likely print "2"
>
> The second anon declaration replaces the Version 1 anon
> function object with a Version 2 object. This is what a
> Version 1 call will access when called the second time.
>
> I think the following will solve the problem. When a function
> is defined its instance is automatically assigned to a
> function local variable of the same name.
>
> def somename():
> once:
> somename.attr = somevalue # "somename" is local to
> function, like a closure.
> do_something(somename) # also local "somename" access.
>
> # Though bad form, changing the name of function "somename"
> to "foo" and # identifier "somename" to something else at the
> module level does not break # the function now known as
> "foo". Within its code block "foo" will always # be
> "somename". foo = somename somename = something_else
>
> This is not be a problem with the init: section since the
> outer function identifier is referencing the proper function
> object during the function declaration.
>
> P.S. This mechanism could also be applied to the object
> statement so that reusing a prototype name at the module
> level, though again not good form, will not break previous
> prototypes created under that name.
Doesn't this have the danger of confusing the user by doing a hidden
shadowing? He may code something expecting to see the outer.func
change.