Python - generator already executing

EDIT the now deleted question was about what the following sentence means

You have to spawn (at least) one session per thread.

My phrasing is far from ideal. So better forget about that sentence :sweat_smile:

The key take away is that you can share driver objects across threads, but not sessions, transactions, or result objects.

Here's one example of what not to do.

import concurrent.futures

import neo4j


URL = "neo4j://localhost:7687"
AUTH = ("neo4j", "pass")


def work_shared_driver(driver: neo4j.Driver):
    with driver.session(database="neo4j") as session:
        print("shared driver", session.run("RETURN 1").to_eager_result())


def work_shared_session(session: neo4j.Session):
    print("shared session", session.run("RETURN 1").to_eager_result())


with neo4j.GraphDatabase.driver(URL, auth=AUTH) as driver:
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        # cool, can do!
        futures = [executor.submit(work_shared_driver, driver)
                   for _ in range(5)]
        for future in futures:
            future.result()

        # not cool, can't do!
        with driver.session(database="neo4j") as session:
            futures = [
                # don't share sessions across threads!
                # this can lead to all sorts of hard to decipher errors
                executor.submit(work_shared_session, session)
                for _ in range(5)
            ]
            for future in futures:
                future.result()
1 Like