Skip to content

Generic function decorated with functools.cache returns the wrong type #100708

@adonig

Description

@adonig

Bug report

A generic function decorated with functools.cache returns the wrong type sometimes. Try this example:

from decimal import Decimal
from functools import cache
from typing import SupportsRound, TypeVar

_T = TypeVar("_T")


@cache
def rnd(val: SupportsRound[_T]) -> _T:
    return round(val, 2)


def test_rnd():
    actual = rnd(Decimal("123"))
    assert actual == Decimal("123")
    assert type(actual) == Decimal
    actual = rnd(123.0)
    assert actual == 123.0
    assert type(actual) == float

My understanding is that the test should run without raising any errors but instead the last assertion fails:

./xxx/tests/test_cache.py::test_rnd Failed: [undefined]AssertionError: assert <class 'decimal.Decimal'> == float
 +  where <class 'decimal.Decimal'> = type(Decimal('123.00'))
def test_rnd():
        actual = rnd(Decimal("123"))
        assert actual == Decimal("123")
        assert type(actual) == Decimal
        actual = rnd(123.0)
        assert actual == 123.0
>       assert type(actual) == float
E       AssertionError: assert <class 'decimal.Decimal'> == float
E        +  where <class 'decimal.Decimal'> = type(Decimal('123.00'))

xxx/tests/test_cache.py:19: AssertionError

Your environment

  • CPython versions tested on: Python 3.11.0
  • Operating system and architecture: Darwin mbp 22.1.0 Darwin Kernel Version 22.1.0: Sun Oct 9 20:14:54 PDT 2022; root:xnu-8792.41.9~2/RELEASE_X86_64 x86_64

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions