sqlalchemy2-stubs
sqlalchemy2-stubs copied to clipboard
Can't infer type from @declared_attr on function __tablename__
Describe the bug
Receiving an error when using @declared_attr decorator on __tablenane__ class method.
Expected behavior Not receiving an error.
To Reproduce
from uuid import UUID, uuid4
from sqlalchemy import Column
from sqlalchemy.orm import as_declarative, declared_attr
from sqlalchemy_utils import Timestamp, UUIDType, generic_repr
@as_declarative()
@generic_repr
class BaseModel(Timestamp):
__name__: str
uuid: UUID = Column(
UUIDType(native=True),
primary_key=True,
default=uuid4,
unique=True,
index=True,
)
@declared_attr
def __tablename__(cls) -> str:
return f"{cls.__name__}s"
Error
[SQLAlchemy Mypy plugin] Can't infer type from @declared_attr on function '__tablename__'; please specify a return type from this function that is one of: Mapped[<python type>], relationship[<target class>], Column[<TypeEngine>], MapperProperty[<python type>]
Versions.
- OS: Linux Mint 20.1
- Python: 3.7.10
- SQLAlchemy: 1.4.17
- mypy: 0.812
- SQLAlchemy2-stubs: 0.0.2a1
Additional context
It also happens for columns with UUID (same example) if you don't specify a type on left hand side. It happens when using UUIDType from sqlalchemy_utils or UUID from sqlalchemy.dialects.postgresql.
Have a nice day!
This may a plugin issue. cc @bryanforbes
Getting the same error on this class
import re
from typing import Any
from sqlalchemy.orm import as_declarative, declared_attr
@as_declarative()
class Base:
id: Any
__name__: str
# Generate __tablename__ automatically
@declared_attr
def __tablename__(cls) -> str:
name = cls.__name__
# It is a regex that matches CamelCase and replaces it with snake_case
# https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case
return re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()
Installed via SQLAlchemy = {extras = ["mypy"], version = "^1.4.23"}