Python Forum
run a string or str as a statement
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
run a string or str as a statement
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Have you tried exec() ?
>>> def func(s):
...     a = 3
...     exec(s, locals(), locals())
... 
>>> func('''
... b = 9
... print(a * b)
... ''')
27
Reply
#3
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
(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
Skaperen likes this post
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020