question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Declared attributes aren't supported

See original GitHub issue

I’m using SQLAlchemy’s declared_attr decorator to add columns and relationships.

However, the decorated columns and relationships are completely ignored.

Here is a very simplified reproducer:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.declarative.api import declared_attr
from sqlalchemy.orm import relationship
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import Integer


Base = declarative_base()


class Person(Base):
    __tablename__ = 'people'

    id = Column(Integer, primary_key=True)
    

class EmailAddress(Base):
    __tablename__ = 'emails'

    @declared_attr
    def owner_id(self) -> Column:
        return Column(Integer, ForeignKey('people.id'), nullable=False)
    
    @declared_attr
    def owner(self) -> relationship:
        return relationship(Person)


me = Person()
email_address = EmailAddress(owner=me)

This is what mypy says:

$ pipenv run mypy decl_attr.py 
decl_attr.py:30: error: Unexpected column "owner" for model "EmailAddress"

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:12
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
subhamagrcommented, Jan 8, 2021

Any updates on this feature request?

0reactions
aydumoulincommented, Jan 26, 2022

@wbobeirne thanks for trying it out and your feedback

As a sidenote In editor Pylance type checking sometimes produces errors due to lack of mypy plugin support. Is mypy producing the same errors when ran on this file?

This is an expunged version of the solution I use in our codebase. The following code runs in production and passes mypy and pylance.

from typing import TYPE_CHECKING, cast
from uuid import UUID

from sqlalchemy import Column


if TYPE_CHECKING:
    CStr = Column[str]
    CUUID = Column[UUID]
else:
    CStr = str
    CUUID = UUID

class _TypedBase:
    """typed base for mypy purposed"""

    external_id: CStr
    revision_id: CUUID

class _BaseModel(_TypedBase):
    """
    In order to defined common foreign key we need to declare it in a mixin class
    -> Columns with foreign keys to other columns must be declared as @declared_attr callables on declarative mixin classes.
    """

    @declared_attr
    def external_id(self):
        return Column(String(512), nullable=False)

    @declared_attr
    def revision_id(self):
        return cast(CUUID, Column(UUID, ForeignKey("revisions.id", ondelete="CASCADE"))

class User(Model, _BaseModel):
    """user"""

    __tablename__ = "users"

    email = Column(String, nullable=False)
    first_name = Column(String(254), nullable=False)
    last_name = Column(String(254), nullable=False)
    deleted_at = Column(DateTime, nullable=True)

    def __init__(self):
        self.external_id = "test"

See the hover tooltip

Capture d’écran 2022-01-26 à 14 47 16

Read more comments on GitHub >

github_iconTop Results From Across the Web

xml validation failed with attribute required and attribute not ...
the problem is that the attribute id has been declared global(direct child of xs:schema). therefore, the attribute id should be qualified ...
Read more >
"The 'MaxOccurs' attribute is not supported in this context ... - IBM
Symptom. "The 'MaxOccurs' attribute is not supported in this context" when attempting to create a new map using an XML Schema.
Read more >
Tools attributes reference | Android Studio
Android Studio supports a variety of XML attributes in the tools namespace that enable design-time features or compile-time behaviors.
Read more >
Attributes in Clang — Clang 16.0.0git documentation
Specified values violate subtarget specifications;; Specified values are not compatible with values provided through other attributes.
Read more >
Error Explanations for The W3C Markup Validation Service
You have used the attribute named above in your document, but the document type you are using does not support that attribute for...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found