Skip to content

Strange behavior when using imports with module prefix #151

@sasanjac

Description

@sasanjac

I noticed some really strange behavior. Given the following example:

from __future__ import annotations

import datetime
import pathlib
import uuid
from enum import Enum
from typing import TYPE_CHECKING
from typing import Optional

from pydantic import BaseModel
from pydantic import Field

if TYPE_CHECKING:
    from typing import Union


VERSION = "1.1.0"


class VoltageSystemType(Enum):
    AC = "AC"
    DC = "DC"


class Meta(BaseModel):
    date: datetime.date  # date of export
    version = VERSION
    name: str
    id: uuid.UUID = Field(default_factory=uuid.uuid4)
    project: Optional[str] = None  # project the export is related to

    class Config:
        frozen = True


class Base(BaseModel):
    @classmethod
    def from_file(cls, path: Union[str, pathlib.Path]) -> Base:
        return cls.parse_file(path)

    def to_json(self, path: Union[str, pathlib.Path], indent: int = 2) -> bool:
        path = pathlib.Path(path)
        path.parent.mkdir(parents=True, exist_ok=True)
        with open(path, "w+") as f:
            f.write(self.json(indent=indent))
        return True

    @classmethod
    def from_json(cls, json_str: str) -> Base:
        return cls.parse_raw(json_str)

doesn't report any violations, although I should get

powerfactory_utils/schema/base.py:3:1: TC003 Move built-in import 'datetime' into a type-checking block

because type-checking-pydantic-enabled is false.

When I do the following changes

    id: uuid.UUID = Field(default_factory=uuid.uuid4) -> id: uuid.UUID #= Field(default_factory=uuid.uuid4)
    path = pathlib.Path(path) -> # path = pathlib.Path(path)

I get

powerfactory_utils/schema/base.py:3:1: TC003 Move built-in import 'datetime' into a type-checking block
powerfactory_utils/schema/base.py:4:1: TC003 Move built-in import 'pathlib' into a type-checking block
powerfactory_utils/schema/base.py:5:1: TC003 Move built-in import 'uuid' into a type-checking block

so everything is working correctly.

When I import uuid4 directly and change

    id: uuid.UUID = Field(default_factory=uuid.uuid4) -> id: uuid.UUID = Field(default_factory=uuid4)
    path = pathlib.Path(path) -> # path = pathlib.Path(path)

I also get the violations.

I think it has to do with using imports with their module prefix that keeps these violations from getting detected.
Can anyone reproduce this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions