connor-makowski / type_enforced

A pure python type enforcer for annotations. Enforce types in python functions and methods.
MIT License
45 stars 2 forks source link

Type mismatch for typed variable `return`. Expected one of the following `['list[str]']` but got `<class 'list'>` instead. #27

Closed creme332 closed 10 months ago

creme332 commented 10 months ago

I am using python 3.9.18 and type-enforced 1.2.0 and the following code causes an error:


from __future__ import annotations
import type_enforced

@type_enforced.Enforcer
class foo:
    def __init__(self):
        pass

    def bar(self) -> list[str]:
        return ["hello", "world"]

foo().bar() # error here

Error produced:

Exception has occurred: TypeError
(foo.bar): Type mismatch for typed variable `return`. Expected one of the following `['list[str]']` but got `<class 'list'>` instead.
  File "/home/mcl/githubrepos/project/src/test.py", line 15, in <module>
    print(foo().bar())
TypeError: (foo.bar): Type mismatch for typed variable `return`. Expected one of the following `['list[str]']` but got `<class 'list'>` instead.

Any help is appreciated. Thanks.

connor-makowski commented 10 months ago

Thanks for creating an issue. I am able to reproduce your error.

It appears that an easy fix is to remove:

from __future__ import annotations

That line modifies the way annotations are handled (they are postponed). This prevents the type_enforced package from being able to handle annotations correctly as python stores them differently under the hood.

This postponed structure will possibly be introduced as the default in python4, but we will not add support for it until it is official. Originally, this was supposed to be the case in python3.10, however it keeps getting pushed back.

Please close this issue if it is resolved.

creme332 commented 10 months ago

Thank you. I had from __future__ import annotations in my code because it fixes an error that Pylance threw when I use union types as such int | float. By removing from __future__ import annotations, I had to use another syntax for union types: [int | float].

Reference: