On Thu, 16 Aug 2018, 12:44 Jacob Solinsky, <jacobsolin...@gmail.com> wrote:
> I wanted the called, jumped to function to change state in the caller. > From what I tried to do, passing locals() cannot accomplish this. I have > made it happen in other languages though. > In the R language, one can do this > > foo = function(){ > localenv = environment() > eval(bar, environment = localenv) > > The above code captures the environment of the calling function and > executes the called function as if the calling function's local environment > was the global environment. bar doesn't have to be a function, it can be > any valid R expression captured with the expr() function, and everything in > R is an expression thus allowing for the full usage code blocks. Outside of > lisp-like languages this feat seems to usually be impossible though. > > > On Thu, 16 Aug 2018, 12:34 Jonathan Fine, <jfine2...@gmail.com> wrote: > >> Hi Chris >> >> Steve and you wrote: >> >> >> there >> >> are times where I have really wanted to access the caller's >> environment, >> >> not the environment where my function was defined. >> >> > what am I missing? can't you get that by passing locals() in to a >> function? >> >> I think this will fail when values are changed. According to >> https://docs.python.org/3/library/functions.html#locals >> > The contents of this dictionary should not be modified; changes may not >> affect the values of local and free variables used by the interpreter. >> >> I suspect that Jacob, the original poster, wants to change state, and >> also to read changed state. Jacob, could you confirm or correct, that >> you want the called function to be able to change state in caller (or >> perhaps even further up the stack). >> >> To finish, here's an interactive example of changing the value of >> locals(). >> >> >>> def f(a=1): loc = locals(); yield loc; yield a >> >>> it = f() >> >>> ctx = next(it) >> >>> ctx >> {'a': 1} ## This surprised me. >> >>> >> >>> >> >>> def f(a=1): loc = locals(); yield locals(); yield a >> >>> it = f() >> >>> ctx = next(it) >> >>> ctx >> {'a': 1, 'loc': {...}} >> >>> ctx['a'] = 3 >> >>> ctx['loc']['a'] = 5 >> >>> next(it) ## Is it 1 or 3 or 5? >> 1 ## The value of 'a' hasn't changed. >> >> -- >> Jonathan >> _______________________________________________ >> Python-ideas mailing list >> Python-ideas@python.org >> https://mail.python.org/mailman/listinfo/python-ideas >> Code of Conduct: http://python.org/psf/codeofconduct/ >> >
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/