How to convert a string to a function name in python?

前端 未结 9 2048
迷失自我
迷失自我 2020-11-27 12:55

For example, if I have a function called add like

def add(x,y):
    return x+y

and I want the ability to convert a string or a

9条回答
  •  失恋的感觉
    2020-11-27 13:27

    I've had many situation where I've needed to compare a string to an int and vice versa within a Django template.

    I created a filter that allowed me to pass in the function name and using eval() convert it.

    Example:

    Template:

    {% ifequal string int|convert:'str' %} do something {% endifequal %}
    

    Template Filter (where i use a string to call the function name):

    @register.filter
    def convert(value, funcname):
        try:
            converted = eval(funcname)(value)
            return converted
        except:
            return value
    

提交回复
热议问题