test_compare_initvar.py


Overview

`test_compare_initvar.py` is a concise Python module demonstrating the use of `InitVar` within a `dataclass`. It primarily illustrates how initialization-only variables (`InitVar`) behave differently from regular instance attributes in terms of equality comparison between dataclass instances. This file contains a single dataclass `Foo` and a test function `test_demonstrate()` that asserts the equality of two `Foo` instances with identical `InitVar` but differing regular attribute values.

The file serves as an educational or experimental snippet to clarify that `InitVar` fields are used only during initialization and are **not** stored as instance attributes, and consequently, do not contribute to equality (`__eq__`) comparisons.


Detailed Explanation

Imports and Decorators

Class Foo

@dataclass
class Foo:
    init_only: InitVar[int]
    real_attr: int

Function test_demonstrate

def test_demonstrate():
    assert Foo(1, 2) == Foo(1, 3)

Important Implementation Details


Interactions with Other System Components

This file is likely a standalone test or example module used for:

It does not import or export any functionality beyond its own scope and does not interact directly with other components or modules in the system.


Visual Diagram

The following Mermaid class diagram depicts the structure of the `Foo` dataclass and its attributes.

classDiagram
    class Foo {
        <<dataclass>>
        +InitVar[int] init_only
        +int real_attr
    }

Summary

`test_compare_initvar.py` is a minimal demonstration of Python `dataclasses` featuring an `InitVar` to show how such fields differ from regular attributes in their lifecycle and effect on instance comparison. It highlights that `InitVar`s are initialization-only and do not affect instance equality.

The included test function aims to reveal this behavior but contains an assertion that will fail under normal circumstances, serving as a prompt for deeper investigation or learning.


Appendix: Typical Behavior Demonstration

f1 = Foo(1, 2)
f2 = Foo(1, 3)
print(f1 == f2)  # Expected output: False because real_attr differs

This snippet clarifies that equality depends only on stored attributes (`real_attr`), not on `InitVar` fields.


**End of Documentation**