How do I apply unknown arguments to a function in Python 3.x?

梦想与她 提交于 2020-01-16 19:39:39

问题


I'm developing my own GUI for my engine, and I've created an "object" called EwConsole (A simple "drop-down" console to input commands). In order to do that, I simply store an ID for the function to be "triggered with enter/return" as the key to the function-object itself in a dict. My problem is with the arguments, and Python 3.x.

Here's my method for creating a new "console command":

def create_command(self, command_id, command_function):
    self["commands"][command_id] = command_function

I've developed my own input object, called "EwInput", which has a method that returns the string value that has been written in it. In order to separate the arguments of the stored command, I split the spaces of the string. Here's the code that "watches" for "commands" in the console:

def watch_for_commands(self):
    if push_enter():
        values = self["input"].get_value().split()
        if values[0] in self["commands"]:
            if len(values) == 1:
                self["commands"][values[0]]()
            elif len(values) > 1:
                try:
                    self["commands"][values[0]](values[1:]) # Problem here.
                except TypeError:
                    raise ErgameError("The given function '{0}' does not support the given arguments: {1}.".format(values[0], values[1:]))
        else:
            print("There is no such command: {}".format(values[0]))

As you can see, since the "command creation" is completely generic, it's not possible to know how many arguments the given function will have. As one can see here, in the old 2.x, it was possible to use "apply" with a list of arguments.

Now comes the question:

How, in Python 3.x, can I "apply" an unknown number of arguments to a function, if it is forcing me to use "__ call __"??? Is there a way in Python 3.x to apply an arbitrary SEQUENCE of arguments to an unknown function?


回答1:


Try using argument unpacking.

self["commands"][values[0]](*values[1:])


来源:https://stackoverflow.com/questions/28031725/how-do-i-apply-unknown-arguments-to-a-function-in-python-3-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!