假设我们要定义一个继承自 的自定义通用(基)类typing.Generic。
为了简单起见,我们希望它由单个类型变量 T来参数化。所以类的定义是这样开始的:
from typing import Generic, TypeVar
T = TypeVar("T")
class GenericBase(Generic[T]):
...
Run Code Online (Sandbox Code Playgroud)
T 有没有办法访问 的任何特定子类中的类型参数GenericBase?
该解决方案应该足够通用,能够在具有附加基础的子类中工作GenericBase,并且独立于实例化(即在类级别上工作)。
期望的结果是这样的类方法:
class GenericBase(Generic[T]):
@classmethod
def get_type_arg(cls) -> Type[T]:
...
Run Code Online (Sandbox Code Playgroud)
class Foo:
pass
class Bar:
pass
class Specific(Foo, GenericBase[str], Bar):
pass
print(Specific.get_type_arg())
Run Code Online (Sandbox Code Playgroud)
输出应该是<class 'str'>.
如果所有相关的类型注释都已完成,以便静态类型检查器可以正确推断get_type_arg.
我有一个函数将返回一个字典,例如:
from typing import Dict
def foo() -> Dict[]:
params = {
"side": "Buy",
"symbol": "BTCUSDT",
"order_type": "Market",
"time_in_force": "PostOnly",
"reduce_only": False,
"close_on_trigger": False,
}
return {
"method": "POST",
"api": "private/linear/order/create",
"body": params
}
Run Code Online (Sandbox Code Playgroud)
里面的内容应该是什么Dict[]?
我刚刚阅读了PEP 586。在动机中,作者这样说:
numpy.unique 将返回单个数组或包含两个到四个数组的元组,具体取决于三个布尔标志值。
(...)
目前无法表达这些函数的类型签名:PEP 484 不包含任何用于编写签名的机制,其中返回类型根据传入的值而变化。
我们建议添加文字类型来解决这些差距。
但我真的不明白添加Literal类型对此有什么帮助。而且我也不同意这样的说法
PEP 484 不包含任何用于编写签名的机制,其中返回类型根据传入的值而变化。
据我所理解,Union可以在这种情况下使用。
返回类型如何numpy.unique注释Literal?
下面的代码有效,但我收到 PyCharm 的以下警告:
在“(...) -> Any”中找不到参考
__annotations__。
我想这是因为我正在使用Callable. 我没有找到类似的东西Dataclass。我应该使用哪种类型?
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable
@dataclass
class Fruit:
color: str
taste: str
def get_cls() -> Callable:
return Fruit
attrs = get_cls().__annotations__ # <- IDE warning
print(attrs)
Run Code Online (Sandbox Code Playgroud) 以下代码似乎生成两个 mypy 错误:Overloaded function signatures 1 and 3 overlap with incompatible return types和Overloaded function signatures 2 and 3 overlap with incompatible return types; 但所有重载都有不同的签名 - Literal[True]、Literal[False] 和 None 不重叠。
@overload
def func_a(*, a: Literal[False] = ...) -> str:
...
@overload
def func_a(*, a: None = ...) -> str:
...
@overload
def func_a(*, a: Literal[True] = ...) -> int:
...
def func_a(*, a: Optional[bool] = None) -> str | int:
if a:
return 1
return "foo"
var1 …Run Code Online (Sandbox Code Playgroud) 在Python文档中,我们发现:
T = TypeVar('T') # Can be anything
S = TypeVar('S', bound=str) # Can be any subtype of str
A = TypeVar('A', str, bytes) # Must be exactly str or bytes
Run Code Online (Sandbox Code Playgroud)
我们还发现了这段代码:
def repeat(x: T, n: int) -> Sequence[T]:
"""Return a list containing n references to x."""
return [x]*n
def print_capitalized(x: S) -> S:
"""Print x capitalized, and return x."""
print(x.capitalize())
return x
def concatenate(x: A, y: A) -> A:
"""Add two strings or bytes objects together."""
return …Run Code Online (Sandbox Code Playgroud) 我有一个总是返回空列表的函数(这是一个很长的故事),我可以像往常一样只用“list”输入提示,但是指示列表总是相同的会很有用。
我的第一个想法是使用这样的文字:
from typing import Literal
def get_empty_list() -> Literal[[]]:
return []
Run Code Online (Sandbox Code Playgroud)
Mypy 将其标记为无效类型,是否有正确的方法来输入提示始终为空的列表?(显然,我可以输入提示只是一个列表,但这没什么帮助)
明确地说,这是一个始终为空的列表,并且不希望包含任何元素。(例如,与当前为空的列表分开,但稍后可能添加某种类型的元素)。
有人知道如何解决这个问题吗?
Exception has occurred: ImportError
cannot import name 'self' from 'typing' (C:\Users\Piotr\AppData\Local\Programs\Python\Python310\lib\typing.py)
File "C:\Users\Piotr\Downloads\music_bot-main\music_cog.py", line 2, in <module>
from typing import self
ImportError: cannot import name 'self' from 'typing' (C:\Users\Piotr\AppData\Local\Programs\Python\Python310\lib\typing.py)
Run Code Online (Sandbox Code Playgroud)
我想制作一个可以播放音乐的不和谐机器人,但这就是阻止我制作它的问题。
我有一个带有复杂返回类型注释的函数:
\nfrom typing import (Union, List)\n\n# The -> Union[\xe2\x80\xa6] is actually longer than this example:\ndef parse(what: str) -> Union[None, int, bool, float, complex, List[int], List[float], List[complex]]:\n # do stuff and return the object as needed\n\ndef parse_from_something(which: SomeType) -> ????:\n return parse(which.extract_string())\n\n# \xe2\x80\xa6\n\nclass SomeType:\n def extract_string(self) -> str:\n # do stuff and return str\nRun Code Online (Sandbox Code Playgroud)\n如何进行类型注释,parse_from_something以便注释后返回与以下内容相同的类型parse,而不重复它们?
我在这里解决的问题是一个函数可能会发生变化,但它周围的包装器总是返回相同的类型集。我不想重复代码,并且因为这是重构和事后类型注释工作,所以我需要假设我将来会删除可能的返回类型parse,而静态类型检查器可能不会意识到parse_from_something不能再退回这些了。
我有一个这样定义的函数:
def demand_cleaning(df=None, location, output,_input,tables):
Run Code Online (Sandbox Code Playgroud)
我想测试是否df通过(df是熊猫DataFrame)
如果df没有通过,我想做类似的事情
if df is None:
df = pd.read_pickle(tables + "Demand Raw")
Run Code Online (Sandbox Code Playgroud)
但是这个测试现在不起作用。我明白了
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Run Code Online (Sandbox Code Playgroud) python ×10
python-typing ×10
mypy ×2
types ×2
base-class ×1
generics ×1
numpy ×1
overloading ×1
pandas ×1
pep ×1
return ×1
typing ×1