Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Clarify namedtuple member rules#1979

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
yangdanny97 wants to merge5 commits intopython:main
base:main
Choose a base branch
Loading
fromyangdanny97:namedtuple

Conversation

yangdanny97
Copy link
Contributor

@yangdanny97yangdanny97 commentedApr 19, 2025
edited
Loading

This PR clarifies the typing spec around named tuple fields and adds a few conformance test cases:

  • fields are not being allowed to begin with underscore (and its interaction withrename)
  • which members are counted/not counted as fields

Analogous restrictions are outlined in thespec for enums, but they are not present in the spec for named tuples.

Since this is adding new rules to the spec, should I open a discussion in the forum about it?

@yangdanny97yangdanny97 marked this pull request as ready for reviewApril 19, 2025 10:36
@erictraut
Copy link
Collaborator

Yes, please start a thread in the discussion forum. I don't think these changes will be controversial, but we should let the community weigh in.

@yangdanny97
Copy link
ContributorAuthor

@WSH032
Copy link

Hi, I'm not sure if this is the right place for this discussion—if not, please let me know (and sorry!).

I originally raisedthis issue in pyright, but I think here might be a more appropriate place to discuss it.

Suppose I do have members that start with"_":

NT5=namedtuple("NT5", ["abc","_1"],rename=True)# OKNT5(abc="",_1=1)# OK

How can I provide type annotations for them in a.pyi file?

classNT5(NamedTuple):abc:str_1:int# <- HOW ?
  • Can we allow an exemption for field names matching the pattern_{index} (e.g.,_1)?

  • Or, could the spec recommend that even if a type checker rejects a field name like_1, it should still provide type analysis for that field:

    fromcollectionsimportnamedtuplefromtyping_extensionsimportTYPE_CHECKING,NamedTuple,assert_typeifnotTYPE_CHECKING:NT5=namedtuple("NT5", ["abc","_1"],rename=True)# OKelse:classNT5(NamedTuple):abc:str_1:int# type: ignore#        #  ^ suppress false positivent5=NT5(abc="",_1=1)# should be okassert_type(nt5[0],str)assert_type(nt5[1],int)# should be okassert_type(nt5.abc,str)assert_type(nt5._1,int)# should be ok

    Currently, mypy and pyrightbehave differently on this point.

@JelleZijlstra
Copy link
Member

I'm with Eric on the linked issue that this doesn't make sense to support. If you use different types on both arms ofif TYPE_CHECKING, you'll see things like this happen.

Can we allow an exemption for field names matching the pattern_{index} (e.g.,_1)?

No, unless the runtime has that exemption. We should match the runtime behavior.

could the spec recommend that even if a type checker rejects a field name like_1, it should still provide type analysis for that field

Type checkers could do that but I don't think it should be the spec's business to decide how type checkers should proceed once they've detected a type error.

@JelleZijlstra
Copy link
Member

And to give a constructive suggestion for your use case: Maybe just don't use namedtuple? If you require names that start with an underscore, it's not the right tool for the job.

@WSH032
Copy link

Fair enough! Thanks for your quick response! 👍

No, unless the runtime has that exemption

It would be nice iftyping.NamedTuple also supported arename=True option at runtime (I think that's outside the scope of this issue discussion 😂).

And to give a constructive suggestion for your use case: Maybe just don't use namedtuple? If you require names that start with an underscore, it's not the right tool for the job.

I can't control the code on the other end; I can only provide type annotations for it (like in a.pyi file).

The workaround I've come up with for now is:

classNT5(tuple[str,int]):abc:str_1:int__match_args__= ("abc","_1")def__new__(cls,abc:str,_1:int)->Self: ...

But this isn't as straightforward astyping.NamedTuple.

Anyway, thanks for your help! 🙏

WSH032 added a commit to pytauri/pytauri that referenced this pull requestMay 18, 2025
WSH032 added a commit to pytauri/pytauri that referenced this pull requestMay 19, 2025
github-merge-queuebot pushed a commit to pytauri/pytauri that referenced this pull requestMay 20, 2025
* feat: add `ExitRequestApi` and `RunEvent::ExitRequested::api` field* refactor: move `PhysicalPositionF64` to `ext_mod::lib`* feat: add `CloseRequestApi`* feat: add `Theme` and `AppHandle/WebviewWindow::{theme, set_theme}`* feat: add `_NonExhaustive` field to all `#[non_exhaustive]` enums* feat: add `DragDropEvent` and `DragDropEventType`* feat!: `Position.Physical(x, y)` -> `Position.Physical(tuple(x, y))`changed:- `Position.Physical`- `Position.Logical`- `Size.Physical`- `Size.Logical`migration:```pyfrom pytauri import Position, PositionType, Size, SizeTypedef old(pos: PositionType, size: SizeType) -> None:    match pos:        case Position.Physical(x, y):            print(f"Physical position: {x}, {y}")        case Position.Logical(x, y):            print(f"Logical position: {x}, {y}")    match size:        case Size.Physical(w, h):            print(f"Physical size: {w}, {h}")        case Size.Logical(w, h):            print(f"Logical size: {w}, {h}")old(pos=Position.Physical(1, 2), size=Size.Physical(3, 4))def new(pos: PositionType, size: SizeType) -> None:    match pos:        case Position.Physical((x, y)):            print(f"Physical position: {x}, {y}")        case Position.Logical((x, y)):            print(f"Logical position: {x}, {y}")    match size:        case Size.Physical((w, h)):            print(f"Physical size: {w}, {h}")        case Size.Logical((w, h)):            print(f"Logical size: {w}, {h}")new(pos=Position.Physical((1, 2)), size=Size.Physical((3, 4)))```* feat: add `WebviewEvent`, `WebviewEventType`added:- `WebviewEvent`- `WebviewEventType`- `RunEvent.WebviewEvent.event` field- `webview.WebviewWindow.on_webview_event` method* feat: add `WindowEvent`, `WindowEventType`added:- `WindowEvent`- `WindowEventType`- `RunEvent.WindowEvent.event` field- `webview.WebviewWindow.on_window_event` method* fix: namedtuple member name can't start with underscoreref: <python/typing#1979 (comment)>* docs: changelog
@erictraut
Copy link
Collaborator

The change looks good to me, but you'll need to update the branch, resolve merge conflicts, and re-run the tests with the latest versions of the type checkers.

Thanks for the contribution!

yangdanny97 reacted with thumbs up emoji

@yangdanny97
Copy link
ContributorAuthor

Ok, I've rebased and updated the results.

@erictraut
Copy link
Collaborator

The PR looks good to me, but we need to wait for@carljm and@JukkaL to review and sign off on the changehere.

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Reviewers

@carljmcarljmcarljm approved these changes

@JelleZijlstraJelleZijlstraJelleZijlstra approved these changes

@rchen152rchen152rchen152 approved these changes

@erictrauterictrauterictraut approved these changes

Assignees
No one assigned
Labels
None yet
Projects
None yet
Milestone
No milestone
Development

Successfully merging this pull request may close these issues.

6 participants
@yangdanny97@erictraut@WSH032@JelleZijlstra@carljm@rchen152

[8]ページ先頭

©2009-2025 Movatter.jp