python / python/mypy

Support attrs 20.1's on_setattr=attr.setters.convert

オープン
#10,187 コメント 0 件 リアクション 1 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

feature topic-attrs
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

Feature

Version 20.1 of attrs introduced support for running a field's converter whenever the field is set. Here's an example of it in action:

import re
import attr

@attr.s(auto_attribs=True)
class GHRepo:
    owner: str
    name: str


def parse_ghrepo(s: str) -> GHRepo:
    if (m := re.fullmatch(r'([^/]+)/([^/]+)', s)) is not None:
        return GHRepo(owner=m[1], name=m[2])
    else:
        raise ValueError(s)


@attr.s
class Foo:
    repo: GHRepo = attr.ib(converter=parse_ghrepo, on_setattr=attr.setters.convert)

f = Foo("owner/name")
f.repo = "python/mypy"  # mypy errors on this line
print(f)

This prints out Foo(repo=GHRepo(owner='python', name='mypy')), as the "python/mypy" assigned to f.repo is converted to a GHRepo with parse_ghrepo().

Unfortunately, mypy as of both version 0.812 and commit 28034cc does not recognize the typing implications of on_setattr=attr.setters.convert, as running it on the above code with the default settings gives the error Incompatible types in assignment (expression has type "str", variable has type "GHRepo") on the marked line. I would like to request that mypy recognize the setting's typing implications and allow thus-configured fields to be set to the input types of their converters.

Pitch

This feature would provide greater support for attrs and allow for defining fields that are initialized & set by converting from other types.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、提示された Python の例を mypy で再現し、attrs の converter の型が現在どのように推論されているかを確認します。Issue では具体的なファイルやテストが示されていないため、作業では関連する attrs plugin と代入チェックのパスを特定する必要があります。示された代入が、他の型チェックを弱めることなく受け入れられれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
devtools
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。