Skip to content

Allow omitting initializer for Final attributes in dataclasses #5608

Closed

Description

@ilevkivskyi

Dataclasses typically don't have __init__, so this is rejected, but is probably valid:

@dataclass
class C:
    x: int
    y: Final[int]

A possible solution is that plugin should set the final_set_in_init flag manually for the corresponding field Vars.

Activity

  1. jcrist commented on Mar 25, 2023

    @jcrist

    I just ran into this. pyright allows these type annotations as is (Final indicates an instance variable), and discussion in python/cpython#89547 seems to indicate this is what'd be most ergonomic to support. It also matches how dataclasses itself handles these annotations.

    For now, a workaround is to add # type: ignore on the annotation line. The dataclass definition still seems to be processed correctly, this just skips the error about a missing initializer.

    import dataclasses
    from typing import Final
    
    
    @dataclasses.dataclass
    class Test:
        # The `type: ignore` is needed here to avoid an error due to a missing
        # initializer
        x: Final[int]  # type: ignore
    
    
    t = Test(1)  # Signature still inferred properly
    reveal_type(t.x)
    t2 = Test("bad")  # Which means mypy marks this as an error
    $ mypy ex.py 
    ex.py:13: note: Revealed type is "builtins.int"
    ex.py:14: error: Argument 1 to "Test" has incompatible type "str"; expected "int"  [arg-type]
    Found 1 error in 1 file (checked 1 source file)
    

    For my own use cases, it'd be nice if the fix here also applied to the recent dataclass_tranform support, so this fix could work for other dataclass-like things as well.

  2. tmke8 commented on May 13, 2024

    @tmke8
    Contributor

    The typing spec now specifies that this should be allowed: python/typing#1669

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions