English 中文(简体)
我如何界定只接受一系列扼杀或一系列愤怒作为理由的职能?
原标题:How can I define a function to accept only either an array of strings or an array of integers as an argument?

I would like to define a function with the parameter specified as "array of strings" or "array of integers", without looping through the individual array elements to check the type of each. Specifically, I would like the function to only allow passing of the two above-mentioned array types in order to run, in the same way one would be able to specify function(param: str) to only accept strings, for example.

我将单独的职能定义为<条码>功能(第1段:名单/代码>或<条码>功能(第24段:名单/代码)。 但是,我无法说明如何同时执行。

问题回答

You can use typing to hint at what this should be, but to really assert the values, you ll need to check them all
conveniently, all() will short-circuit on the first non-Truthy value

Typing

from typing import Union

def function(param: Union[list[str], list[int]):
    ...

1. 执业

def function(param):
    for test_type in (int, str):
        try:
            if all(type(v) == test_type for v in param):
                break  # escape the for loop
        except TypeError as ex:  # param is not iterable
            if "is not iterable" in str(ex):
                raise TypeError(f"param must be iterable, but got {type(param)})" from ex
            raise ex  # pass through other errors
    else:  # did not break out of for loop
        raise TypeError("function only accepts homogenous iterables of int or str")
    ...  # rest of function

注:这只是允许<代码>第>>为任何iterable的略为允许的,但你可以走到前面,坚持你喜欢的任何东西——但认识到,这一设计将消耗发电机,因此,要收集和维护其价值的工作将会更多(从理论上讲,带有评论和用法的警告器往往比试图强迫他们使用你打算使用的工具)好。

我仍是一个起点,但我将努力:

IDK 如何做到这一点,但你可以检查第一个要素,并与清单的其他部分进行比较。

def func(param: list):
  if type(param[0])!=int and type(param[0])!=str:
    raise Exception("this function accepts only array of integers or array of strings")
  for i in range(1,len(param)):
    if type(param[i]) != type(param[0]):
      raise Exception("this function accepts only array of integers or array of strings")




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签