【发布时间】:2021-03-19 08:27:20
【问题描述】:
我编写了简单的代码来处理一种情况,并更正包含使用 def 关键字声明的 Python 函数的字符串的缩进(同样简单,它依赖于用户在使用时要小心)并执行它.
def fix_index(string):
i=0;
t=string.find("def")+3;
string=string.replace(string[string.find("def"):t], "@")
while string.find(" ") != -1:
string = string.replace(" ", "")
i += 1
l=list(string);l[string.find(":")-i+2]+="$$$$"
return "".join(l).replace("$$$$", " ").replace("@", "def ").lstrip();
def switch(exp):
def exec(obj):
items = obj.items();
for k, v in items:
if(k==exp):
print(fix_index(v))
return eval(fix_index(v))();
return {"case":exec};
bread = "bread"
switch(bread)["case"]({
"cheese":
"""
def a():
print("cheese");
""",
"bread":
"""
def b():
print("bread");
"""
})
格式化函数字符串的输出:
C:\Users\User>python -u "c:\Users\User\folder\switch.py"
def b():
print("bread");
我得到的错误:
Traceback (most recent call last):
File "c:\Users\User\folder\switch.py", line 27, in <module>
switch(bread)["case"]({
File "c:\Users\User\folder\switch.py", line 21, in exec
return eval(fix_index(v))();
File "<string>", line 1
def b():
^
SyntaxError: invalid syntax
我也刚刚意识到我没有将函数命名为我缩进的意图(应该在清醒时发布此内容以避免意外双关语)。
无论如何,我无法理解的是我生成的字符串中的哪一部分恰好包含“无效语法”。
我将不胜感激。
【问题讨论】:
-
def是一个语句,eval仅适用于表达式。你想要exec -
但是,呃,无论你在这里尝试做什么,看起来你都不应该使用任何一个
-
同意。我认为你最好使用 lambdas
标签: python string parsing switch-statement eval