简体   繁体   English

lambda 赋值方式

[英]lambda way to assign a value

In my python code, I want to assign the "name" value into " request_body " based on the input, something as if:在我的 python 代码中,我想根据输入将“名称”值分配给“ request_body ”,就像:

def make_api_call(context, name, ...):
    api_name = f"<my_API_Call_URL_here>"
    request_body= {}
    request_body["name"] = lambda name:  "" if name == "BLANK" else name
    ...
    context.base.execution_call(context, api_name, request_body, "post")

    

Is that the correct way in lambda to have the string value assigned to request_body["name"] ?这是 lambda 中将字符串值分配给request_body["name"]的正确方法吗?

Somehow, when I to make the api call in the end, I have got such error message:不知何故,当我最后进行 api 调用时,我收到了这样的错误消息:

TypeError: Object of type function is not JSON serializable

lambda is an alternative way to create a small function and there's no need for it in your case. lambda是创建小函数的另一种方法,在您的情况下不需要它。 You should use something like:你应该使用类似的东西:

request_body["name"] = "" if name == "BLANK" else name

You can't use a lambda to "assign a value" without calling it:你不能使用 lambda 来“赋值”而不调用它:

>>> a = lambda name: "" if name == "BLANK" else name
>>> type(a)
<class 'function'>

if you want your lambda that bad try this如果你想让你的 lambda 变得那么糟糕,试试这个

test_name = lambda x:  "" if x == "BLANK" else x
request_body["name"] = test_name(name)

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

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