【问题标题】:Indenting Python function within string and executing it using eval在字符串中缩进 Python 函数并使用 eval 执行它
【发布时间】: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


【解决方案1】:

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

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

它使用不重复切换值的 if/elif/else 条件使用单遍 for 循环来模拟 switch 语句:

例如:

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

【讨论】:

    猜你喜欢
    • 2021-06-18
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2020-09-21
    • 2021-01-01
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多