Python -- 只有在变量存在时才传递参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16576553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python -- Only pass arguments if the variable exists
提问by user1328021
I have the following variables that a user can optionally submit through a form (they are not required, but may do this to filter down a search).
我有以下变量,用户可以选择通过表单提交这些变量(它们不是必需的,但可以这样做来过滤搜索)。
color = request.GET.get ('color')
size = request.GET.get ('size')
Now I want to pass these variables to a function, but only if they exist. If they do not exist I want to just run the function without arguments.
现在我想将这些变量传递给一个函数,但前提是它们存在。如果它们不存在,我只想运行没有参数的函数。
the function without arguments is:
没有参数的函数是:
apicall = search ()
with color only it's
只有颜色
apicall = search (color)
and with color and size it's
和颜色和大小
apicall = search (color, size)
If the argument is defined I want to pass it to the function, but if it's not I do not want to pass it.
如果定义了参数,我想将它传递给函数,但如果不是,我不想传递它。
What is the most efficient way to do that? Does python have built-in methods for this?
最有效的方法是什么?python 有内置的方法吗?
采纳答案by Henry Keiter
Assuming that's a standard getcall (like on a dictionary), this ought to be easy. Define your function with Nonefor the defaults for your parameters, and then pass colorand sizewithout bothering to check them!
假设这是一个标准get调用(如字典),这应该很容易。使用None参数的默认值定义您的函数,然后通过color而size无需费心检查它们!
def apicall(color=None, size=None):
pass # Do stuff
color = request.GET.get('color')
size = request.GET.get('size')
apicall(color, size)
This way, you only check for Nonearguments in one place (inside the function call, where you have to check anyway if the function can be called multiple ways). Everything stays nice and clean. Of course this assumes (like I said at the top) that your getcall is like a normal Python dictionary's getmethod, which returns Noneif the value isn't found.
这样,您只None在一个地方检查参数(在函数调用内部,无论如何您必须检查该函数是否可以通过多种方式调用)。一切都保持美好和干净。当然,这假设(就像我在顶部get所说的那样)您的调用就像一个普通的 Python 字典的get方法,None如果没有找到该值,它就会返回。
Finally, I notice that your function name is apicall: there's a chance you don't actually have access to the function code itself. In this case, since you may not know anything about the default values of the function signature and Nonemight be wrong, I would probably just write a simple wrapper to do the argument-checking for you. Then you can call the wrapper as above!
最后,我注意到您的函数名称是apicall:您实际上可能无法访问函数代码本身。在这种情况下,由于您可能对函数签名的默认值一无所知并且None可能是错误的,因此我可能只会编写一个简单的包装器来为您进行参数检查。然后你可以像上面一样调用包装器!
def wrapped_apicall(color=None, size=None):
if color is None and size is None:
return apicall()
# At least one argument is not None, so...
if size is None:
# color is not None
return apicall(color)
if color is None:
# size is not None
return apicall(size)
# Neither argument is None
return apicall(color, size)
NOTE:This second version shouldn't be necessaryunless you can't see the code that you're calling and don't have any documentation on it! Using Noneas a default argument is very common, so chances are that you can just use the first way. I would only use the wrapper method if you can't modify the function you're calling and you don't know what its default arguments are (or its default arguments are module constants or something, but that's pretty rare).
注意:除非您看不到正在调用的代码并且没有任何文档,否则不需要第二个版本!使用None的默认参数是很常见的,所以有机会,你可以只使用第一种方式。如果您无法修改正在调用的函数并且您不知道它的默认参数是什么(或者它的默认参数是模块常量或其他东西,但这种情况很少见),我只会使用包装器方法。
回答by Kevin London
When you're defining your method, if you set a default argument you can specify the argument or not.
当你定义你的方法时,如果你设置了一个默认参数,你可以指定或不指定参数。
def search(color=None, size=None):
pass
Then, when you call it, you can specify the keyword argument as you choose. Both of these would be valid:
然后,当您调用它时,您可以根据需要指定关键字参数。这两个都是有效的:
apicall = search(color=color)
apicall = search(size=size)
回答by mijailr
Maybe you can use something like this:
也许你可以使用这样的东西:
try:
apicall = search (color, size)
except:
apicall = search(color)
回答by Blairg23
As much as I like @HenryKeiter's solution, Python provides a MUCH easier way to check the parameters. In fact, there are a couple different solutions.
尽管我喜欢@HenryKeiter的解决方案,但 Python 提供了一种更简单的方法来检查参数。事实上,有几种不同的解决方案。
- For example, if
search()is a standalone function and you want to view the args, you can use the inspectmodule as seen in this solution.
Example Code 1
示例代码 1
>>> import inspect
>>> print(inspect.getfullargspec(search))
ArgSpec(args=['size', 'color'], varargs=None, keywords=None, defaults=(None, None))
- However, if
search()is a method of a class (we'll call itSearch), then you can simply do use the built-in varsfunction to see all of the class methods and their parameters:
- 但是,如果
search()是类的方法(我们称之为Search),那么您可以简单地使用内置的vars函数来查看所有类方法及其参数:
Example Code 2
示例代码 2
>>> import Search
>>> print(vars(Search))
mappingproxy({'__init__': <function Search.__init__(self, size, color)>,
'search': <function Search.search(self, size, color)})
The only caveat with the 2nd method is that it's more useful as a visual inspection tool, rather than a programmatic one, although you could technically say if 'size' in vars(Search)['search']: do something. It just wouldn't be very robust. Easier and more durable to say if 'size' in inspect.getfullargspec(Search.search).args: do somethingor for arg in inspect.getfullargsspec(Search.search).args: do something
第二种方法的唯一警告是,它作为视觉检查工具更有用,而不是编程工具,尽管从技术上讲,您可以说if 'size' in vars(Search)['search']: do something. 它只是不会很健壮。更容易和更耐用的说if 'size' in inspect.getfullargspec(Search.search).args: do something或for arg in inspect.getfullargsspec(Search.search).args: do something
回答by AdamAL
In python 3 you could pack them up in a list, filter it, and use the *-operator to unpack the list as arguments to search:
在 python 3 中,您可以将它们打包到一个列表中,对其进行过滤,然后使用*-operator 将列表作为参数解压到search:
color = request.GET.get ('color')
size = request.GET.get ('size')
args = [ arg for arg in [color, size] if arg ]
search(*args)
Note, however, if coloris falsy and sizeis truthy, you would be calling searchwith 1 argument being the value of size, which would probably be wrong, but the original question doesn't mention desired behaviour in that case.
但是请注意,如果color是假的并且size是真的,您将search使用 1 个参数作为 的值进行调用size,这可能是错误的,但原始问题并未提及在这种情况下所需的行为。
(necromancing since I was looking for a better solution than mine, but found this question)
(死灵,因为我正在寻找比我更好的解决方案,但发现了这个问题)

