小编Ale*_*ood的帖子

从数据类的 __str__ 表示中排除一些属性

我们有这个类:

from dataclasses import dataclass, field
from datetime import datetime
from typing import List, Dict

@dataclass
class BoardStaff:
    date: str = datetime.now()
    fullname: str
    address: str

    ## attributes to be excluded in __str__:
    degree: str
    rank: int = 10
    badges: bool = False
    cases_dict: Dict[str, str] = field(default_factory=dict)
    cases_list: List[str] = field(default_factory=list)

Emp = BoardStaff('Jack London', address='Unknown', degree='MA')
Run Code Online (Sandbox Code Playgroud)

作为BoardStaff数据类,可以轻松print(Emp)地接收:
BoardStaff(fullname='Jack London', address='Unknown', degree='MA', rank=10, badges=False, cases={}, date=datetime.datetime(2021, 8, 10, 11, 36, 50, 693428)).

但是,我希望从表示中排除一些属性(即最后 5 …

python attributes class python-dataclasses

2
推荐指数
1
解决办法
69
查看次数

如何让 mypy 全局忽略丢失的导入?

我有许多导入其他非类型化库的文件。

我已将此添加到mypy.ini例如:

[coloredlogs]
ignore_missing_imports = True
Run Code Online (Sandbox Code Playgroud)

那么也许这可以不检查库本身?例如,在 a/venv但仍在 every.single.place 中导入了一个库,我收到这些警告。

我可以让忽略工作的唯一方法是在 every.single.import 上添加注释

import coloredlogs # type: ignore

参考文献:https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports

python type-hinting mypy python-typing

2
推荐指数
1
解决办法
3021
查看次数

如何输入常量并集

我想做以下事情:

from typing import Union, Literal
YES = 1
NO = 0
ValidResponse = Union[Literal[YES], Literal[NO]]
Run Code Online (Sandbox Code Playgroud)

当然,Python 不会让我这样做,因为YESNO被认为是变量,而不是文字数字。

显然我可以做到ValidResponse = Union[Literal[1], Literal[0]],但作为稍后编辑此文件的程序员,为了更改YES使用的常量(例如YES = 'yes'),我需要在两个不同的地方更改它,这似乎很奇怪。

处理这种情况的最佳方法是什么?

python type-hinting python-typing

1
推荐指数
1
解决办法
1430
查看次数

如何从类属性动态设置类方法返回类型

我正在从事我的一个宠物项目,发现了这个小问题。我想在基类中使用类型,问题是类方法的返回类型是由子类设置的字段定义的。这是我的基类

class BaseRepository(metaclass=RequiredAttributes('model')):

    model = None  # The subclasses have to define the this field with a class type.
                  # All the class methods will return objects of the same
                  # type as this field.

    def get(self, id) -> ??:
        # return an object of the type defined in mode
        ...


class UserRepo(BaseRepository): # subclass

    model = User # class type

    ...


Run Code Online (Sandbox Code Playgroud)

我想将函数的类型设置get为与模型字段中定义的对象类型相同。

关于如何完成类似的事情有什么建议吗?

python type-hinting python-3.x python-typing

1
推荐指数
1
解决办法
1378
查看次数

如何在不确定返回类型的情况下表达python可调用类型?

我有一个函数返回另一个函数,但返回函数的返回类型不清楚。为了表达我们可以使用的函数返回类型Callable[[], ReturnType],并且不强调参数,我们可以这样做Callable[..., ReturnType]。但我希望这ReturnType不是确定的。

我该怎么办?

我的代码是这样的:

def funcA() -> int:
  return 2

def funcB() -> str:
  return 'b'

def f(inp: int) -> Callable[[], X] # <--- what should X be Here?
  return funcA if inp == 0 else funcB
Run Code Online (Sandbox Code Playgroud)

python type-hinting python-typing

1
推荐指数
1
解决办法
39
查看次数

类型提示数组

考虑以下最小示例:

from array import array


def foo(arr: array) -> None:
    print(arr)
Run Code Online (Sandbox Code Playgroud)

我有一个带有参数的函数array。我的项目是静态类型的并使用mypy。Mypy 抱怨说: Mypy: Missing type parameters for generic type "array".

你能帮我理解我应该如何输入提示参数吗?我似乎找不到有关该主题的文档。我不明白为什么 mypy 会认为这是一个通用类型。

为了澄清,根据我的理解,我使用的类型提示有效,但 mypy 仍然抱怨,因为它认为它是通用类型,并且想要“元素”的类型。我是否遗漏了什么,或者是 mypy 中的错误?

与此相关: 数组的类型提示是什么?

python arrays type-hinting mypy python-typing

1
推荐指数
1
解决办法
3923
查看次数

带参数的自定义类型提示

我时不时地发现自己定义一个带有参数的函数,该参数可以是类型的单个实例,也可以是同一类型的序列。当类型本身已经很复杂时,类型提示可能很快就会变得模糊。

而不是类似的东西

my_dicts: Union[Dict[str, int], Sequence[Dict[str, int]]] 
Run Code Online (Sandbox Code Playgroud)

我想定义一个快捷方式,这样我就可以输入

my_dicts: SingleOrSequence[Dict[str, int]] 
Run Code Online (Sandbox Code Playgroud)

我该如何以最Pythonic的方式解决这个问题?另请记住,为了与其他类型保持一致,调用签名应类似于上面的内容,即指定自定义类型名称并直接用方括号传递包含的类型。

我能想到的最好的看起来像这样:

import typing

class SingleOrSequenceClass():
    @staticmethod
    def __getitem__(typ):
        return typing.Union[typ, typing.Sequence[typ]]
    
SingleOrSequence = SingleOrSequenceClass() 
Run Code Online (Sandbox Code Playgroud)

这确实有效,但特别是必须实例化 SingleOrSequenceClass 并不适合我。关于如何改进这一点有什么建议吗?打字模块本身是否为此提供了任何优雅的解决方案?

python type-hinting python-typing

1
推荐指数
1
解决办法
2265
查看次数

简化多个 try 和 except 语句

我的功能是做什么的:

  1. 通过处理文件夹内容(/tmp/A、/tmp/B 等)创建一个 war 文件
  2. 进行一些文件路径和文件夹路径操作以从 war 文件获取最终版本。
  3. 将文件名存储在一个变量中,将版本存储在另一个变量中。
  4. 使用curl 将war 文件推送到存储库。

我使用多个 try & except 块来捕获每个操作的异常,并且看起来非常不Pythonic。

有没有一种优雅而简单的方法来解决这个问题?提前致谢。

import shutil
import traceback
import subprocess
import os
import glob


def my_function(path_a, path_b, tmp_dir)

    try:
        <shutil.copy to the tmp dir>
    except:
        traceback.print_exc()

    try:
        war_process = subprocess.run([WAR GENERATION COMMAND], check=True,  stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        print(war_process.stdout.decode("utf-8"))
    except subprocess.CalledProcessError as e:
        exit_code = e.returncode
        stderror = e.stderr
        print(exit_code, stderror)
        print(war_process.stderr.decode("utf-8"))

    try:
        output_folder = os.path.join("/tmp/dir/work", FILE_PATH, ARTIFACT_DATE, FILE_WO_EXTENSION)
    except:
        traceback.print_exc()
    try:
        file_name = list(glob.glob(os.path.join(output_folder, "*.war")))
    except:
        traceback.print_exc()
    try: …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

1
推荐指数
1
解决办法
333
查看次数

Python 类型提示与数字

我刚刚遇到了 Python 类型提示的奇怪行为。

>>> def x(y: int):
    return y
>>> d=x('1')
>>> print(type(d))
<class 'str'>
>>> d
'1'
Run Code Online (Sandbox Code Playgroud)

当我将数字作为字符串传递到参数被转换为 int 的函数时,它仍然会生成字符串。我认为这种意想不到的行为的关键在于它不是铸造,而是暗示。但为什么它会这样呢?如果我传递“one”作为参数,它会给我一个 NameError。

python type-hinting python-typing

0
推荐指数
1
解决办法
994
查看次数

使用多个命令的列表理解

我正在为文件列表创建输出文件。在例程结束时,我想获取输出文件名的列表,我可以使用下面的 for 块来实现该列表。有没有一种干净的方法可以使用列表理解来做这样的事情,或者现在不是理解的好时机?

import os

names = []
for file in f_list:
    base, ext = os.path.splitext(file)
    names.append(f"{base}_env{ext}")
Run Code Online (Sandbox Code Playgroud)

下面的代码有效,但如果我无法摆脱 os.path.splitext 的重复调用,我对此并不感到兴奋。

[f"{os.path.splitext(file)[0]}_env{os.path.splitext(file)[1]}" for file in list]

python list-comprehension filepath

0
推荐指数
1
解决办法
274
查看次数