在哪里保留Python类方法返回类型?

发布于 2025-02-10 04:27:31 字数 1312 浏览 0 评论 0原文

我有一个用于提出HTTP请求的Python模块,以及用于进行数据库调用的不同模块。我正在使用 dict-dict-typy 生成第三API JSON响应和MongoDB实体的键入。 dict- typer 在使用它们或外部的方法的同一模块中?

由于通常,一种方法返回使用自定义类型,我相信该类型应与同一模块中的方法绑定,但随后将其吹向源文件。另一个问题是,何时有更多自定义响应类型具有某些字段,其名称相同。

我当前的解决方案会产生许多文件,因为我将每个响应类型都移至独立模块以避免:

  • 类型的名称碰撞
    • 响应类型
    • 响应字段类型
  • 炸毁客户端文件
class AFieldType(TypedDict):
  a: str
  b: str
  ...

class AResponse(TypedDict):
  a: AFieldType
  b: str
  ...

# A partial type `AFieldType` which feels conflicting
class AFieldTypePartial1(TypedDict):
  a: str
  ...

class AFieldTypePartial2(TypedDict):
  a: str
  ...

class BResponse(TypedDict):
  a: AFieldTypePartial1
  b: str
  ...

class BVariant1Response(TypedDict):
  ...

class BVariant2Response(TypedDict):
  ...

class FooClient:
  def get_A() -> AResponse:
    pass
  def get_B() -> BResponse:
    pass
  def get_B_variant1() -> BVariant1Response:
    pass
  def get_B_variant2() -> BVariant2Response:
    pass

     

I have a python module for making HTTP requests and a different one for making database calls. I'm generating typing for the 3rd API JSON response and the MongoDB entities using dict-typer.
What is the best place to store tons of custom return data types for the class methods generated by dict-typer? In the same module of the method that uses them or outside?

Since usually, one method returns with a custom type, I believe the type should be tied to the method in the same module, but then it blows up the source file. Another issue is when more custom response type has some fields with the same name that conflicts.

My current solution produces many files since I move every response type to a standalone module to avoid:

  • type name collisions of
    • response type
    • response field type
  • blowing up the client file
class AFieldType(TypedDict):
  a: str
  b: str
  ...

class AResponse(TypedDict):
  a: AFieldType
  b: str
  ...

# A partial type `AFieldType` which feels conflicting
class AFieldTypePartial1(TypedDict):
  a: str
  ...

class AFieldTypePartial2(TypedDict):
  a: str
  ...

class BResponse(TypedDict):
  a: AFieldTypePartial1
  b: str
  ...

class BVariant1Response(TypedDict):
  ...

class BVariant2Response(TypedDict):
  ...

class FooClient:
  def get_A() -> AResponse:
    pass
  def get_B() -> BResponse:
    pass
  def get_B_variant1() -> BVariant1Response:
    pass
  def get_B_variant2() -> BVariant2Response:
    pass

     

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文