i would like to be able to run a string (or at least just a str) as a statement in the current context (for example, its local variables being the same as the current context locals, unlike a function). if the string has newline character(s) then those divide lines just as if multiple lines were in the code at this point (recognizing indentation). how difficult would this be to implement? i'm assuming it would be rather difficult because of the possible adding of different variables to the compiled fixed local context. any suggestions?
Have you tried
exec()
?
>>> def func(s):
... a = 3
... exec(s, locals(), locals())
...
>>> func('''
... b = 9
... print(a * b)
... ''')
27
documentation for exec() (PDF version) has:
Output:
Note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.
the part "modifications to the default locals dictionary should not be attempted" is the issue. i want to have the full current context, including modifiable locals.
(Sep-11-2023, 05:21 PM)Skaperen Wrote: [ -> ]i want to have the full current context, including modifiable locals.
Use a copy of locals()
c = 5
def func(s):
a = 3
d = dict(locals())
exec(s, globals(), d)
print(d)
if __name__ == '__main__':
s = """
global c
b = 10
c = 13
print(a * b)
"""
func(s)
print(c)
Output:
λ python paillasse/skapexec.py
30
{'s': '\nglobal c\nb = 10\nc = 13\nprint(a * b)\n', 'a': 3, 'b': 10}
13