2

We use Python sets extensively and need to insert data from sets into our Postgres DB, which doesn't have a similar data type. We'd like to insert all sets into the DB as arrays. We could do that by wrapping all sets with list(), but it would be nice to write a simple psycopg2 adaptor instead. I've looked at the docs, but it's unclear how to do it.

1 Answer 1

3

You can do it by registering an adapter for the set type and use the adapt function to treat the set as a list. This'll give the set the necessary getquoted() function from the list, which'll turn it into ARRAY[x,y,...] in the SQL string. See the code below.

from psycopg2.extensions import register_adapter, adapt
def adapt_set(my_set):
    return adapt(list(my_set))
register_adapter(set, adapt_set)
Sign up to request clarification or add additional context in comments.

1 Comment

Figured out the solution after drafting the question so tried the Q&A style answer. Hope it's helpful to anyone!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.