Python dynamic function creation with custom names

后端 未结 6 2312
深忆病人
深忆病人 2020-11-27 18:07

Apologies if this question has already been raised and answered. What I need to do is very simple in concept, but unfortunately I have not been able to find an answer for it

6条回答
  •  感情败类
    2020-11-27 18:59

    You may want to use eval; you'll build the string containing the Python definition of each function (i.e. a multiline string starting with def func1 ....) and you'll then eval it.

    But I would generate a unique name for each such function (e.g. genfun345). Don't use some unchecked user input for such names. Because if the name is the same as some known name in Python, you are going into a difficult to debug disaster.

    Do you trust the inputs from which these functions are made? Do you care about malware or abuse?

    Read about hygenic macros on wikipedia.

提交回复
热议问题