在字符串中缩进Python函数并使用eval执行它



我只编写了一个简单的代码来处理一种情况,并更正包含使用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:UsersUser>python -u "c:UsersUserfolderswitch.py"
def b():
print("bread");

我得到的错误:

Traceback (most recent call last):
File "c:UsersUserfolderswitch.py", line 27, in <module>
switch(bread)["case"]({
File "c:UsersUserfolderswitch.py", line 21, in exec
return eval(fix_index(v))();
File "<string>", line 1
def b():
^
SyntaxError: invalid syntax

我也刚刚意识到,我并没有把函数命名为我缩进的意图(应该在清醒时发布,以避免意外双关(。

无论如何,我不明白的是,我产生的字符串中到底包含什么部分;无效语法";。

我将感谢任何帮助。

如果您想要的是重现一个switch语句,您可以使用以下函数:

def switch(v): yield lambda *c: v in c

它使用if/elif/else条件下的循环单次传递来模拟切换语句,这些条件不重复切换值:

例如:

for case in switch(x):
if    case(3):     
# ... do something
elif  case(4,5,6): 
# ... do something else
else:              
# ... do some other thing

它也可以用于更C风格:

for case in switch(x):
if case(3):     
# ... do something
break
if case(4,5,6): 
# ... do something else
break 
else:              
# ... do some other thing

例如,它可能看起来像这样:

meal = "bread"
for case in switch(meal):
if   case("cheese"):
print("Cheese!")
elif case("bread"):
print("Bread!")

或者这个:

meal = "bread"
for case in switch(meal):
if case("cheese"):
print("Cheese!")
break
if case("bread"):
print("Bread!")
break

最新更新