sqlalchemy: support dataclass defaults that don't affect subsequent ORM operations

The use case for this is mainly dataclass defaults, so that we can use mapped_column(default=<new-constrant-here>) and that’s equivalent to not setting the field at all.

This should also work for relationships:

Some considerations from other discussions:

i think one area that we have a choice to make is if you have an object with state and you say, myobject.foo = NO_VALUE - does that expire the attribute or just do nothing? I vote for the latter https://github.com/sqlalchemy/sqlalchemy/discussions/12165#discussioncomment-11509551

I guess the behaviour wanted is

thing = session.get(Thing, 1)
assert thing.foo == 'bar'
thing.foo = NO_VALUE
assert thing.foo == 'bar'

and if foo is expired it stays expired, so

thing = session.get(Thing, 1)
session.expire(thing, 'foo')
assert 'foo' in sa.inspect(x).expired_attributes
thing.foo = NO_VALUE
assert 'foo' in sa.inspect(x).expired_attributes

In the above example either behaviour is fine. Not sure if before assert thing.foo == 'bar' in the first example ‘foo’ should be in the expired_attributes or not. I trust your insight here if you prefer for not. https://github.com/sqlalchemy/sqlalchemy/discussions/12165#discussioncomment-11510441

Connected discussions:

Target is 2.0.x but may be moved to 2.1 depending on the changes

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 32 (22 by maintainers)

Commits related to this issue

Most upvoted comments

It seems to me that this is the most adequate way.

There is a simple Default type that you can wrap a value in. We can call self.is_default and if we get True, do not add the value to session methods.

DefaultArg = TypeVar("DefaultArg")


class Default(Generic[DefaultArg]):
    def __init__(self, value: DefaultArg):
        self.value = value

    def __repr__(self) -> DefaultArg:
        return f"{self.value}"

    def unwrap(self) -> DefaultArg:
        return self.value


class Base(DeclarativeBase):

    def __getattribute__(self, name: str):
        value = super().__getattribute__(name)
        if isinstance(value, Default):
            return value.unwrap()
        return value

    def is_default(self, name: str) -> bool:
        value = super().__getattribute__(name)
        return isinstance(value, Default)


class User(Base, MappedAsDataclass, kw_only=True):
    __tablename__ = 'user'

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    status: Mapped[str | None] = mapped_column(default=Default("ACTIVE"))
    is_paid: Mapped[bool] = mapped_column(default=Default(False))


user = User(id=1, name="John")

print(user.status)
> ACTIVE
print(type(user.status)
> <class 'str'>
print(isinstance(user.status, str))
> True
print(user.is_default("status"))
> True

The advantage is that we can hide this construction in the library implementation and get the same behavior for standard values ​​in regular models and MappedAsDataclass, fixing the original problem https://github.com/sqlalchemy/sqlalchemy/discussions/12165

As a result, the code will not be different, are you using a regular model or MappedAsDataclass:

class User(Base, MappedAsDataclass, kw_only=True):
    __tablename__ = 'user'

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    status: Mapped[str | None] = mapped_column(default="ACTIVE")  << Default("ACTIVE")
    is_paid: Mapped[bool] = mapped_column(default=False)  << Default(False)

Also, using this approach, we can add an exclude_default or exclude_unset method to the mapped_column and allow users to choose whether they want to exclude the default value or not.

class User(Base, MappedAsDataclass, kw_only=True):
    __tablename__ = 'user'

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    status: Mapped[str] = mapped_column(default="ACTIVE", exclude_unset=False)
    is_paid: Mapped[bool] = mapped_column(default=False, exclude_unset=True)

By updating the user, we obviously understand that he is active, but in order not to explicitly indicate his status each time, we will simply specify exclude_unset=False and rely on the default value.