Skip to content
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

false positive attribute error with dataclasses and metaclasses #1594

Open
crazystick opened this issue Feb 28, 2024 · 0 comments
Open

false positive attribute error with dataclasses and metaclasses #1594

crazystick opened this issue Feb 28, 2024 · 0 comments
Labels
bug cat: control flow control flow analysis

Comments

@crazystick
Copy link

Given the following code:

import dataclasses
from enum import EnumMeta, Enum
from typing import Optional, Union


class MyEnumMeta(EnumMeta):
    """Metaclass for Enum classes"""


class MyEnum(Enum, metaclass=MyEnumMeta):
    FIRST = "thing1"


@dataclasses.dataclass
class Holder:
    thing: Optional[Union[MyEnum, str]] = dataclasses.field(default=None)

    def to_dto(self):
        return {
            "thing": self.thing.value if isinstance(self.thing, MyEnum) else self.thing
        }


def test_enums():
    none_thing = None
    enum_thing = MyEnum.FIRST
    string_thing = "thing2"

    my_value = none_thing.value if isinstance(none_thing, MyEnum) else none_thing
    assert my_value is None
    my_value = enum_thing.value if isinstance(enum_thing, MyEnum) else enum_thing
    assert my_value == "thing1"
    my_value = string_thing.value if isinstance(string_thing, MyEnum) else string_thing
    assert my_value == "thing2"

    holder = Holder(thing=None)
    assert holder.to_dto() == {"thing": None}
    holder = Holder(thing=enum_thing)
    assert holder.to_dto() == {"thing": "thing1"}
    holder = Holder(thing=string_thing)
    assert holder.to_dto() == {"thing": "thing2"}


if __name__ == "__main__":
    test_enums()

    print("Everything passed")

produces the following errors:

File "enum_error.py", line 20, in to_dto: No attribute 'value' on None [attribute-error]
  In Optional[Union[Any, str]]
Called from (traceback):
  line 45, in current file
  line 37, in test_enums
File "enum_error.py", line 20, in to_dto: No attribute 'value' on str [attribute-error]
  In Optional[Union[Any, str]]
Called from (traceback):
  line 45, in current file
  line 37, in test_enums

However no error is produced if you remove the dataclass (i.e. just assigning to my_value), and also no error is produced when removing the metaclass from MyEnum

@rchen152 rchen152 added bug cat: control flow control flow analysis labels Mar 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug cat: control flow control flow analysis
Projects
None yet
Development

No branches or pull requests

2 participants