簡體   English   中英

在字符串中縮進 Python function 並使用 eval 執行它

[英]Indenting Python function within string and executing it using eval

我編寫了簡單的代碼來處理一種情況並更正包含使用def關鍵字聲明的 Python function 的字符串的縮進(同樣簡單,它依賴於用戶在使用時要小心)並執行它。




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");
    """
})


output 用於格式化的 function 字符串:

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

我也剛剛意識到我沒有將function命名為我想要的(應該在清醒時發布以避免意外雙關語)。

無論如何,我無法理解的是我生成的字符串中的哪一部分恰好包含“無效語法”。

我會很感激任何幫助。

如果您正在尋找的是重現 switch 語句,您可以使用以下 function 來實現:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM