简体   繁体   English

为给定的 URL 保存 function 参数的最佳方法

[英]Best way to save function params for a given URL

I have an endpoint with some required and optional parameters:我有一个带有一些必需和可选参数的端点:

Required: ID [str]必需:ID [str]

Optional: name_1 [str], regex [boolean], ignore_case [boolean]可选:name_1 [str]、regex [boolean]、ignore_case [boolean]

I want to build a function to use this endpoint:我想构建一个 function 来使用这个端点:

import requests

def get_function(ID, name_1=None, regex=None, ignore_case=None):

    url= 'heretheurl/{ID}'.format(ID)

    params = {}

    if name_1 is not None:
        params.update({'name_1':name_1})
    if regex is not None:
        params.update({'regex':regex})
    if ignore_case is not None:
        params.update({'ignore_case':ignore_case})

    response = requests.get(url, params=params)

Is it a better way to do this avoiding all these IF s?这是避免所有这些 IF 的更好方法吗?

You could use **kwargs for the convenience of having the params in a dictionary rather than a bunch of local variables that are then harder to deal with, but then enforce that only certain keyward arguments are acceptable, and for anything else, raise a TypeError .您可以使用**kwargs以方便将参数放在字典中,而不是一堆难以处理的局部变量,然后强制只接受某些 keyward arguments ,对于其他任何事情,引发TypeError . (You could instead have an explicit argument list and then use locals() , but it will include other local variables, so it could get messy.) (您可以改为使用显式参数列表,然后使用locals() ,但它会包含其他局部变量,因此可能会变得混乱。)

import requests

def get_function(ID, **kwargs):

    supported_args = {'name_1', 'regex', 'ignore_case'}
    for key in kwargs:
        if key not in supported_args:
            raise TypeError(f"{key} not supported")

    url = 'heretheurl/{ID}'.format(ID=ID)

    params = dict((k, v) for k, v in kwargs.items() if v is not None)
    
    response = requests.get(url, params=params)


get_function("blah", name_1="stuff", ignore_case=True)

BTW, your format usage is wrong in the line starting url = (you are mixing the usage for keyword and positional parameters), so I've corrected this.顺便说一句,在url =开头的行中,您的format使用错误(您正在混合使用关键字和位置参数),所以我已经纠正了这一点。


The first version of this answer said raise a ValueError if the argument is not supported, but I have changed it to TypeError in order to match what is raised when an unexpected keyword argument is passed while using an explicit argument list.这个答案的第一个版本说如果不支持参数,则引发ValueError ,但我已将其更改为TypeError以匹配在使用显式参数列表时传递意外关键字参数时引发的内容。

import requests

def get_function(ID, **kwargs):
    url= 'heretheurl/{ID}'.format(ID)
    response = requests.get(url, params=kwargs)

I guess you could say:我想你可以说:

for local, value in locals().items():
    if value is not None:
        params[local] = value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM