带有注释ы作为GO结构样式

发布于 2025-02-10 00:29:08 字数 1988 浏览 1 评论 0原文

Python Dataclasses真的很棒。他们允许以非常美丽的方式定义课程。

from dataclasses import dataclass

@dataclass
class InventoryItem:
    """Class for keeping track of an item in inventory."""
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand

此外,许多有用的工具以相同的方式重复使用Python注释,并允许以相同的方式定义类(更像其他语言的结构)。一个示例之一是 pydantic

from pydantic import BaseModel


class User(BaseModel):
    id: int
    name = 'John Doe'
    signup_ts: Optional[datetime] = None
    friends: List[int] = []

这些天我自己使用了很多pydantic。从我最近的实践中看一个例子:

class G6A(BaseModel):
    transaction_id: items.TransactionReference # Transaction Id
    mpan_core: items.MPAN # MPAN Core
    registration_date: items.CallistoDate # Registration Date
    action_required: G6AAction # Action Required

我解析了一些非常不便的API,这就是为什么我想对每一行发表评论。因此,它将作为自我证明。问题是,至少对我来说,这看起来很丑陋。看上去很难投掷线,因为看起来像桌子的桌子。让我们尝试通过做准确的凹痕来解决此问题:

class G6A(BaseModel):
    transaction_id:     items.TransactionReference  # Transaction Id
    mpan_core:          items.MPAN                  # MPAN Core
    registration_date:  items.CallistoDate          # Registration Date
    action_required:    G6AAction                   # Action Required

我敢肯定,这种方式更可读。通过这样做,我们定义结构,例如实际表,其中1列是属性名称,2列为属性类型,最后一个是注释。它实际上是受到GO structs启发的

type T struct {
    name    string // name of the object
    value   int    // its value
}

,所以我的问题是 - 是否有任何自动工具(Linters)会像我上面描述的那样重新格式化数据级/pydantic -Models?我看上去扔了autopep8,黑色衬里,什么也没找到。还谷歌搜索了,依此类推,仍然没有。有什么想法如何通过现有工具来实现这一目标?

Python dataclasses are really great. They allow to define classes in very beautiful way.

from dataclasses import dataclass

@dataclass
class InventoryItem:
    """Class for keeping track of an item in inventory."""
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand

Moreover lots of useful tools re-use python annotations the same way and allow to define classes (that are more like structures in other languages) the same way. One of the example is Pydantic.

from pydantic import BaseModel


class User(BaseModel):
    id: int
    name = 'John Doe'
    signup_ts: Optional[datetime] = None
    friends: List[int] = []

I myself use pydantic quite a lot these days. Look at an example from my recent practice:

class G6A(BaseModel):
    transaction_id: items.TransactionReference # Transaction Id
    mpan_core: items.MPAN # MPAN Core
    registration_date: items.CallistoDate # Registration Date
    action_required: G6AAction # Action Required

I parse some very inconvenient api and that's why I want to leave a comment on every line. With that it will be working as self-documentation. The problem is that, at least for me, this looks very ugly. It's hard to look throw lines, 'cause the look like table with broken columns. Let's try to fix this by doing accurate indentations:

class G6A(BaseModel):
    transaction_id:     items.TransactionReference  # Transaction Id
    mpan_core:          items.MPAN                  # MPAN Core
    registration_date:  items.CallistoDate          # Registration Date
    action_required:    G6AAction                   # Action Required

I'm sure that this way it is much more readable. By doing so we define structure, like actual table, where 1 column is attribute name, 2 column is attribute type and the last one is comment. It is actually inspired by Go structs

type T struct {
    name    string // name of the object
    value   int    // its value
}

So, my questions is - are there any automatic tools (linters), that will reformat dataclass/pydantic-models the way I described above? I looked throw autopep8, black linter and find nothing. Also googled and so on and still nothing. Any ideas how to achieve that by existing tools ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

莳間冲淡了誓言ζ 2025-02-17 00:29:08

我认为 yapf 有类似的评论。检查space_before_comment“ knob”:

尾随评论之前所需的空间数量。这可以是单个值(表示每个尾随注释之前的空格数)或值列表(表示对齐列值;在块中的尾随注释将与第一列值一致,该列值大于最大线长度块)

.style.yapf

[style]
based_on_style = pep8
spaces_before_comment = 10,20,30,40,50,60,70,80

对齐列:10,20,...,80

class G6A(BaseModel):
    transaction_id: items.TransactionReference # Transaction Id
    mpan_core: items.MPAN # MPAN Core
    registration_date: items.CallistoDate # Registration Date
    action_required: G6AAction # Action Required

配置 /代码>:

class G6A(BaseModel):
    transaction_id: items.TransactionReference   # Transaction Id
    mpan_core: items.MPAN                        # MPAN Core
    registration_date: items.CallistoDate        # Registration Date
    action_required: G6AAction                   # Action Required

I think yapf has something like that for comments. Check the SPACES_BEFORE_COMMENT "knob":

The number of spaces required before a trailing comment. This can be a single value (representing the number of spaces before each trailing comment) or list of of values (representing alignment column values; trailing comments within a block will be aligned to the first column value that is greater than the maximum line length within the block)

.style.yapf:

[style]
based_on_style = pep8
spaces_before_comment = 10,20,30,40,50,60,70,80

Configures alignment columns: 10, 20, ..., 80.

foo.py:

class G6A(BaseModel):
    transaction_id: items.TransactionReference # Transaction Id
    mpan_core: items.MPAN # MPAN Core
    registration_date: items.CallistoDate # Registration Date
    action_required: G6AAction # Action Required

Output of yapf foo.py:

class G6A(BaseModel):
    transaction_id: items.TransactionReference   # Transaction Id
    mpan_core: items.MPAN                        # MPAN Core
    registration_date: items.CallistoDate        # Registration Date
    action_required: G6AAction                   # Action Required
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文