我们可以在打字稿中定义这样的重载函数:
function hello(name: number): void;
function hello(name: string): void;
function hello(name: number | string): void {
// ...
}
Run Code Online (Sandbox Code Playgroud)
我尝试将此函数定义为 const,例如:
const hello = (name: number | string): void => {
// ...
}
Run Code Online (Sandbox Code Playgroud)
但不确定如何在其上声明重载签名:
(name: number): void;
(name: string): void;
Run Code Online (Sandbox Code Playgroud)
请帮忙,谢谢
我想知道以下之间有什么区别:
from pydantic import BaseModel, Field
class Person(BaseModel):
name: str = Field(..., min_length=1)
Run Code Online (Sandbox Code Playgroud)
和:
from pydantic import BaseModel, constr
class Person(BaseModel):
name: constr(min_length=1)
Run Code Online (Sandbox Code Playgroud)
name两者似乎都执行相同的验证(甚至在为空字符串时引发完全相同的异常信息)。这只是代码风格的问题吗?其中一个比另一个更受青睐吗?
另外,如果我想包含一个非空字符串列表作为属性,您认为以下哪种方式更好?:
from typing import List
from pydantic import BaseModel, constr
class Person(BaseModel):
languages: List[constr(min_length=1)]
Run Code Online (Sandbox Code Playgroud)
或者:
from typing import List
from pydantic import BaseModel, Field
class Person(BaseModel):
languages: List[str]
@validator('languages', each_item=True)
def check_nonempty_strings(cls, v):
if not v:
raise ValueError('Empty string is not a valid language.')
return v
Run Code Online (Sandbox Code Playgroud)
编辑:FWIW,我将其用于 FastAPI 应用程序。
编辑2:对于我的第二个问题,我认为第一个替代方案更好,因为它包含架构中的长度要求(因此它在文档中)
请考虑以下代码:
from typing import Callable, Any
TFunc = Callable[..., Any]
def get_authenticated_user(): return "John"
def require_auth() -> Callable[TFunc, TFunc]:
def decorator(func: TFunc) -> TFunc:
def wrapper(*args, **kwargs) -> Any:
user = get_authenticated_user()
if user is None:
raise Exception("Don't!")
return func(*args, **kwargs)
return wrapper
return decorator
@require_auth()
def foo(a: int) -> bool:
return bool(a % 2)
foo(2) # Type check OK
foo("no!") # Type check failing as intended
Run Code Online (Sandbox Code Playgroud)
这段代码按预期工作.现在想象一下我想扩展这个,而不是只是执行func(*args, **kwargs)我想在参数中注入用户名.因此,我修改了函数签名.
from typing import Callable, Any
TFunc = Callable[..., Any] …Run Code Online (Sandbox Code Playgroud) Python 3.7即将到来,我想测试一些奇特的新dataclass+打字功能.使用本机类型和typing模块中的类型,可以很容易地获得正确工作的提示:
>>> import dataclasses
>>> import typing as ty
>>>
... @dataclasses.dataclass
... class Structure:
... a_str: str
... a_str_list: ty.List[str]
...
>>> my_struct = Structure(a_str='test', a_str_list=['t', 'e', 's', 't'])
>>> my_struct.a_str_list[0]. # IDE suggests all the string methods :)
Run Code Online (Sandbox Code Playgroud)
但是我想要尝试的另一件事是在运行时强制类型提示作为条件,即不应该dataclass存在具有不正确类型的类型.它可以很好地实现__post_init__:
>>> @dataclasses.dataclass
... class Structure:
... a_str: str
... a_str_list: ty.List[str]
...
... def validate(self):
... ret = True
... for field_name, field_def in self.__dataclass_fields__.items():
... actual_type = type(getattr(self, …Run Code Online (Sandbox Code Playgroud) 静态类型语言和动态类型语言原则上看起来像是相反的概念.但是,像Objective-C这样的语言如何同时成为这两种东西?在我看来,Objective-C比动态更静态.有人可以解释一下这是可能的吗?
tl;dr在 Rust 中,是否存在“强”类型别名(或类型机制),使得rustc编译器会拒绝(发出错误)可能是相同底层类型的混淆?
目前,可以定义相同底层类型的类型别名
type WidgetCounter = usize;
type FoobarTally = usize;
Run Code Online (Sandbox Code Playgroud)
但是,如果我错误地混淆了两种类型别名的实例,编译器不会拒绝(发出错误或警告)。
fn tally_the_foos(tally: FoobarTally) -> FoobarTally {
// ...
tally
}
fn main() {
let wc: WidgetCounter = 33;
let ft: FoobarTally = 1;
// whoops, passed the wrong variable!
let tally_total = tally_the_foos(wc);
}
Run Code Online (Sandbox Code Playgroud)
(铁锈游乐场)
我希望有一个额外的关键字之类的东西strong
strong type WidgetCounter = usize;
strong type FoobarTally = usize;
Run Code Online (Sandbox Code Playgroud)
这样前面的代码在编译时会导致编译器错误:
error[E4444]: mismatched strong alias type WidgetCounter,
expected a FoobarTally
Run Code Online (Sandbox Code Playgroud)
或者也许 s …
我很难找到满足的返回类型mypy。我有两个功能。第一个返回一个Union类型,因为该类型取决于赋予函数的参数。第二个函数使用默认参数调用第一个函数。因此,该类型不是一种Union类型——它可以缩小到Union.
让我给你举一个我的问题的一个非常简单的例子:
from typing import Union
def first(as_string: bool) -> Union[str, int]:
if as_string:
return "42"
else:
return 42
def second(as_string: bool) -> str:
return first(True)
Run Code Online (Sandbox Code Playgroud)
这会导致错误:
Incompatible return value type (got "str", expected "Union[str, int]")
Run Code Online (Sandbox Code Playgroud)
如何mypy在仍然使用类型提示的同时防止抛出错误?
如果您想建议拆分第一个函数,请记住这只是一个简化。我的(第一个)函数接收一个函数(sklearn.metricsfunction)并且大多数时候会返回一个标量。仅当应用混淆矩阵时,类型才会发生变化。第一个函数进行一些预处理,然后应用度量。我只是想为混淆矩阵提供一个不同名称的函数,因为我认为它是度量的特殊情况。
键入代码时,我通常会关闭括号,返回内部,外出,键入分号等:
我可以从(|是插入符号)开始:
System.out.println()|
Run Code Online (Sandbox Code Playgroud)
然后左转:
System.out.println(|)
Run Code Online (Sandbox Code Playgroud)
然后这个:
System.out.println(foo()|)
Run Code Online (Sandbox Code Playgroud)
再次回溯空间:
System.out.println(foo(|))
Run Code Online (Sandbox Code Playgroud)
输入引号类似:
System.out.println(foo(""|))
Run Code Online (Sandbox Code Playgroud)
...等等.
我的右手在主行和箭头键之间不断移动.我尝试过vim,虽然我知道基础知识,但对我来说仍然感觉很尴尬.
我该怎么做?我应该从左到右键入(打开括号,然后是内容,然后关闭括号,然后是分号)?
谢谢.
我使用importlib.import_module如下动态加载Python模块
def load_module(mod_name: str) -> ???:
return importlib.import_module(mod_name)
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我模块类型的正确类型注释是什么.该typing模块不包含一个,我在其他地方找不到答案.
我正在尝试使用该--strict选项,tsc但我遇到了以下"奇怪"的情况,我似乎并不理解.
如果我写:
function testStrict(input: {query?: {[prop: string]: string}}) {
if (input.query) {
Object.keys(input.query).forEach(key => {
input.query[key];
})
}
return input;
}
Run Code Online (Sandbox Code Playgroud)
编译器抱怨:
test.ts(5,9):错误TS2532:对象可能是"未定义的".
(违规行是input.query[key];)
我不明白的是,我已经在函数的第一行用if guard检查了undefined if (input.query),为什么编译器认为它可能是未定义的?
我通过在对象访问之前添加另一个相同的防护来修复此问题,例如:
function testStrict(input: {query?: {[prop: string]: string}}) {
if (input.query) {
Object.keys(input.query).forEach(key => {
if (input.query) {
input.query[key];
}
})
}
return input;
}
Run Code Online (Sandbox Code Playgroud)
但我不明白为什么需要另一条相同的线.
typing ×10
python ×5
typescript ×2
coding-style ×1
decorator ×1
dynamic ×1
fastapi ×1
mypy ×1
objective-c ×1
overloading ×1
pydantic ×1
python-3.x ×1
rust ×1
static ×1
tsc ×1
type-hinting ×1
validation ×1