I am trying to execute a String that contains Python code as below.
The Python's features I am implementing to run the String containing Python code are eval and exec
from CodeExecs.Compilers import Code1, Code2, Code3, Code4, Code5, Code6, Code7, Code8, Code9, Code10, Code11, Code12, Code13, Code14, Code15, Code16, Code17, Code18, Code19, Code20
program = """for i in range(1, 21):\n\tif eval(f'Code{i}().load(jobj)'): return 'True'\n\telse: return 'False'"""
print(exec(program))
If the for-loop in program appears obscure, it could be found in the error message at the bottom.
The above code prints True when the case is satisfied (Code1 & Code2). The expression in eval raises an exception for Code3.
So instead of printing, if I try to return True / False as below:
program = """for i in range(1, 21):\n\tif eval(f'Code{i}().load(jobj)'): return 'True'\n\telse: return 'False'"""
print(exec(program))
I see an error:
SyntaxError: 'return' outside function
Below is the full console log with error message.
for i in range(1, 21):
if eval(f'Code{i}().load(jobj)'): return 'True'
else: return 'False'
Traceback (most recent call last):
File "C:/CodeValidation/CheckSchema.py", line 22, in <module>
print(exec(program))
File "<string>", line 2
SyntaxError: 'return' outside function
Could anyone let me know what is the mistake I am doing here and how can I return True or False in my case as given above?
Any help is much appreciated.
eval? Just put the 20Codeclasses in a list:for c in [Code1, ..., Code20]: if c().load(obj): return 'True'.