Skip to content

Instantly share code, notes, and snippets.

@kirang89
Last active November 11, 2022 05:10
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kirang89/22d111737af0fca251e3 to your computer and use it in GitHub Desktop.
Save kirang89/22d111737af0fca251e3 to your computer and use it in GitHub Desktop.
Creating a mutable ARRAY data type in sqlalchemy
class Something(Base):
__tablename__ = 'yaddayadda'
id = Column(Integer, primary_key=True)
data = Column(MutableList.as_mutable(ARRAY(String(100))))
from sqlalchemy.ext.mutable import Mutable
from sqlalchemy.dialects.postgresql import ARRAY
class MutableList(Mutable, list):
def append(self, value):
list.append(self, value)
self.changed()
@classmethod
def coerce(cls, key, value):
if not isinstance(value, MutableList):
if isinstance(value, list):
return MutableList(value)
return Mutable.coerce(key, value)
else:
return value
@gkadillak
Copy link

This was super helpful, thank you! I added a pop method to the list so you can remove items from the list as well. Here's what I'm using right now:

class MutableList(Mutable, list):
  def append(self, value):
    list.append(self, value)
    self.changed()

  def pop(self, index=0):
    value = list.pop(self, index)
    self.changed()
    return value

  @classmethod
  def coerce(cls, key, value):
    if not isinstance(value, MutableList):
      if isinstance(value, list):
        return MutableList(value)
      return Mutable.coerce(key, value)
    else:
      return value

@ROZBEH
Copy link

ROZBEH commented Jun 18, 2020

Hi there,
Do you have a simple working example of this?
Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment