Friday, November 5, 2010

What if called functions could access the variables from the caller?

Of course, normally you just pass the variables you are interested the called function to access as parameters.

But it raises an interesting development paradigm if every non-local variable is looked up on the  scope of each calling function. Some languages, like Postscript, work this way.

In Python it can be achieved simply by copying the local variables in the code-frame of the caller functions to the global scope of the called one:

This decorator, while solid enough for "production" won't  work for variables in functions defined within other functions that use variable names that exist on the outher functions. Those would still be bound to the defining closure, as Free Variables.  It can be made to work with those, but it would be another beast.


  1. Funciona no jython! :-)

    No IronPython não tem o módulo inspect:
    IronPython.Runtime.Exceptions.ImportException: No module named inspect
    at Caller.Call
    at BuiltinFunctionCaller.Call5
    at System.Dynamic.UpdateDelegates.UpdateAndExecute7
    at IronPython.Runtime.Importer.Import
    at IronPython.Runtime.Operations.PythonOps.InitializeModule
    at PythonMain.Main

  2. In jython it works.

    In IronPython, 2.6.2, I forward some steps, but don't achive the goal :-/

    To use the currentframe we need to pass the -X:FullFrames argument.

    c:\>ipy.exe -X:FullFrames
    >>> from inspect import currentframe
    >>> currentframe(0)
    <frame object at 0x000000000000002B>

    But in IronPython the FunctionType raise the NotImplementedError.