【问题标题】:Handling function param that can str or list in Python在 Python 中处理可以 str 或 list 的函数参数
【发布时间】:2019-11-05 01:55:05
【问题描述】:

我不是一个有经验的 Python 程序员,但我觉得我对这个问题的解决方案是不对的,我认为在 Python 中有更好的方法来处理这个问题。

在这种情况下,这是使用 Hug API 但这可能几乎无关紧要。

假设代码是这样的:

@hug.get_post('/hello')
def hello (name)
   print(type(name))
   return name

当使用name 参数的一个实例发送请求时,hello 函数将获得str - 如下所示:

POST /hello?name=Bob

但是如果请求发送多个name参数,该方法接收一个list的字符串,如

POST /hello?name=Bob&name=Sally

如果我编写如下方法:

@hug.get_post('/hello')
def hello (name: list)
   print(type(name))
   return name

那么单个参数就变成了一个字符列表。 IE。 ['B', 'o', 'b']。但如果有多个 name 参数实例(例如 ['Bob', 'Sally'] ),这很好用

所以我现在解决它的方法是添加以下代码:

@hug.get_post('/hello')
def hello (name)
   names=list()
   if type(name) != 'list'
      names.append(name)
   else:
      names=name
   return names

这可行,但感觉不对。我认为有更好的方法可以做到这一点,但我目前无法弄清楚。

【问题讨论】:

  • 这绝对是错误的:if type(name) != 'list' type 的结果永远不会等于字符串。 type 返回一个类对象,所以在这里你可以使用 if type(name) is not list 但你应该使用 isinstance 来做一些更惯用的东西

标签: python hug


【解决方案1】:

Hug 为此提供了一个类型:hug.types.multiple

import hug
from hug.types import multiple

@hug.get()
def hello(name: multiple):
    print(type(name))

    return name

现在/hello?name=Bob 返回['Bob']/hello?name=Bob&name=Sally 返回['Bob', 'Sally']

如果要验证内部元素,可以像这样创建自定义类型:

import hug
from hug.types import Multiple, number

numbers = Multiple[number]()

@hug.get()
def hello(n: numbers):
    print(type(n))

    return n

在这种情况下,/hello?n=1&n=2 返回 [1, 2]/hello?n=1&n=a 导致错误:

{"errors": {"n": "提供的整数无效"}}

【讨论】:

    【解决方案2】:

    如果你想更简洁,你可以像这样使用三元运算符:

    @hug.get_post('/hello')
    def hello (name)
       return name if isinstance(name, list) else [name]
    

    【讨论】:

      【解决方案3】:

      我不确定你能不能用更优雅的方式做到这一点。

      isinstance() 是一种非常常见的检查类型的方法。 下面的代码可以处理元组、列表或字符串

      @hug.get_post('/hello')
      def hello (name):
         if isinstance(name, (list, tuple)):
            names = name
         else:
            names = [name]      
         return names
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-01
        • 1970-01-01
        • 2015-01-04
        • 1970-01-01
        • 1970-01-01
        • 2011-01-26
        • 2019-07-14
        相关资源
        最近更新 更多