我尝试将“参数”类型限制为 int 或列表,如下面的函数“f”。但是,Pycharm 不会在 f("weewfwef") 行显示有关错误参数类型的警告,这意味着此 (parameter : [int, list]) 不正确。
在 Python 中,是否可以将 Python 函数参数的类型限制为两种可能的类型?
def f(parameter : [int, list]):
if len(str(parameter)) <= 3:
return 3
else:
return [1]
if __name__ == '__main__':
f("weewfwef")
Run Code Online (Sandbox Code Playgroud) 如何使用Python类型提示编写函数声明,以便函数返回多个返回值?
是否允许以下语法?
def greeting(name: str) -> str, List[float], int :
// do something
return a,b,c
Run Code Online (Sandbox Code Playgroud) 使用类型提示库typing是否可以组合两种类型?我想要一个 singlestr或 alist of str作为参数。见下文:
from typing import Dict, Optional, List
def run_ml(
estimator: Estimator,
parameters: Optional[Dict[str, List[str]]] = None,
):
Run Code Online (Sandbox Code Playgroud) 我有一些自动生成的代码,它定义了许多具有通用属性的类,例如不幸的是,它们没有基类、接口等。
class A:
errors = []
class B
errors = []
Run Code Online (Sandbox Code Playgroud)
我该如何描述一种类型?我不能轻易改变所有这些类型。
def validate(obj: ???):
if errors:
raise Exception("something wrong")
Run Code Online (Sandbox Code Playgroud) 我有一个 python 函数,它返回具有以下结构的字典
{
(int, int): {string: {string: int, string: float}}
}
Run Code Online (Sandbox Code Playgroud)
我想知道如何使用类型提示来指定它。所以,这些位很清楚:
Dict[Tuple[int, int], Dict[str, Dict[str, # what comes here]]
Run Code Online (Sandbox Code Playgroud)
但是,内部字典具有两个键的int和值类型。float我不知道如何注释
假设我有一个这样的函数:
def A(test=False):
if test:
return 1
return "no value passed in for test"
Run Code Online (Sandbox Code Playgroud)
在 Typescript 中,你可以做类似的事情
function A(test=false) <number | string> {
...
}
Run Code Online (Sandbox Code Playgroud)
但如果我尝试用 Python 做同样的事情,我会得到一个错误。
def A(test=False) -> (int, str):
def A(test=False) -> [int, str]:
def A(test=False) -> int or str:
Run Code Online (Sandbox Code Playgroud)
在处理类型检查中的歧义方面,我对 Python 有了更好的理解。所以这可能不是问题。但我很感兴趣是否有正确的方法可以做到这一点。
我正在使用dataclass装饰器。
对于我的一个变量,我希望它是 astr或int类型
from dataclasses import dataclass
@dataclass
class Foo:
test_var: str
# test_var: int
def get_example(self):
return type(self.test_var)
Run Code Online (Sandbox Code Playgroud)
当对象被构造时,我希望 fortest_var是 astr或 an ;如何为我的类的属性指定两种类型?intFoo
我有一个函数,它的参数应该是integer或string。
from typing import int,str
def MyFunc(arg:int) -> None:
print(arg)
Run Code Online (Sandbox Code Playgroud)
但我想知道如何编写它来告诉用户 arg 可以是 int 和 str 吗?