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

前端 未结 9 1988
迷失自我
迷失自我 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:15

    One safe way is to map from names to functions. It's safer than using eval.

    function_mappings = {
            'add': add,
    }
    
    def select_function():
        while True:
            try:
                return function_mappings[raw_input('Please input the function you want to use')]
            except KeyError:
                print 'Invalid function, try again.'
    
    0 讨论(0)
  • 2020-11-27 13:22

    unutbu's solution is what I would normally use, but for completeness sake:

    If you are specifying the exact name of the function, you can use eval, although it is highly discouraged because people can do malicious things:

    eval("add")(x,y)
    
    0 讨论(0)
  • 2020-11-27 13:23

    I had the same problem.

    The way I recommend you to handle it is to create a temporary Python file to store the function the user input. Here's an example I used in a program I wrote to draw representations of mathematical functions:

    with open("function.py",'w') as file:
        f=input('enter the function you want to draw example: 2*x+1 or e**x :\n')
        file.write("from math import *\ndef f(x):\n\treturn "+f)
    

    This will create a file containing the function I want to call.

    Next, you must call the function you wrote in the file to your program:

    from function import f
    

    Now you can use your function as normal python function.

    If you want, you can also delete the file where you stored your function using os.remove:

    import os
    os.remove("function.py")
    

    To help you understand, here is my program to draw mathematical functions:

    import numpy
    import cv2
    import os
    from math import *
    
    
    def generate(f,a,b,min,max,functionname='noname'):
        ph=(b-a)/1920
        pv=(max-min)/1080
        picture=numpy.zeros((1080,1920))
        for i in range(0,1920):
            picture[1079-(int((f(a+(i+1)*ph)*1080/max))),i]=255
        for i in range(1920):
            picture[1079-(int((f(a+(i+1)*ph)*1080/max)))+1,i]=255
        cv2.imwrite(functionname+'.png',picture)
    
    
    with open("function.py",'w') as file:
        f=input('enter the function you want to draw example: or e**x :\n')
        file.write("from math import *\ndef f(x):\n\treturn "+f)
    
    from function import f
    os.remove("function.py")
    d=input('enter the interval ,min ,max and the image file name. Separate characters with spacebar. Example: 0 1 0 14 exponontielle :\n').split(" ")
    generate(f,int(d[0]),int(d[1]),int(d[2]),int(d[3]),d[4])
    
    0 讨论(0)
  • 2020-11-27 13:25

    Just use function reference:

    def pwr(x, y):
        return x ** y
    
    def add(x, y):
        return x + y
    
    dispatcher = { 'pwr' : pwr, 'add' : add}
    
    def call_func(x, y, func):
        try:
            return dispatcher[func](x, y)
        except:
            return "Invalid function"
    
    call_func(2, 3, 'add')
    

    Simple and secure.

    0 讨论(0)
  • 2020-11-27 13:25

    If you are implementing a shell-like application where the user enter some command (such as add), and the application responses (return the sum), you can use the cmd module, which handles all the command interactions and dispatching for you. Here is an example:

    #!/usr/bin/env python
    
    import cmd
    import shlex
    import sys
    
    class MyCmd(cmd.Cmd):
        def do_add(self, arguments):
            '''add - Adds two numbers the print the sum'''
            x, y = shlex.split(arguments)
            x, y = int(x), int(y)
            print x + y
    
        def do_quit(self, s):
            '''quit - quit the program'''
            sys.exit(0)
    
    if __name__ == '__main__':
        cmd = MyCmd()
        cmd.cmdloop('type help for a list of valid commands')
    

    Here is a sample running session:

    $ python cmd_tryout.py
    type help for a list of valid commands
    (Cmd) help add
    add - Adds two numbers the print the sum
    (Cmd) add 5 3
    8
    (Cmd) quit

    At the prompt (Cmd), you can issue the help command which you get for free. Other commands are add and quit which correspond to the do_add() and do_quit() functions.

    Note that help command displays the docstring for your function. The docstring is a string immediately follows the function declararation (see do_add() for example).

    The cmd module does not do any argument spliting, parsing, so you have to do it yourself. The do_add() function illustrates this.

    This sample program should be enough to get you started. For more information look up the cmd help page. It is trivia to customize the prompt and other aspect of your program.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题