I'm building my own Python REPL and will need to execute statements typed by the user. I saw this post that discusses using setattr
to run assignment statements dynamically. Are there equivalents for executing other types of statements like loops and defining classes, or is exec
the only way to do so?
Asked
Active
Viewed 43 times
0

JRR
- 6,014
- 6
- 39
- 59
-
If the entire goal is to run arbitrary user-supplied code, you might as well use `exec`. Just make sure you understand the consequences of that goal - for example, if you're planning to offer this as an online service, you'll have to run the interpreter in some kind of secure sandbox and not trust it in any way. – user2357112 Jun 24 '20 at 01:26
-
The point of using things like `setattr` instead of `exec` is to *avoid* the possibility of running untrusted code. – user2357112 Jun 24 '20 at 01:27
-
I understand. And that's exactly what I am looking for to avoid calling exec to run other type of user code like while loops. – JRR Jun 24 '20 at 01:34
-
not exactly sure this is relevant and would help but, could you try using docker to containerize each code run by the user? would that offset some of the issues of using ```exec```? – griffin_cosgrove Jun 24 '20 at 22:00