Python functions with extra invisible param?

Viewed 36

I am using the Python driver for Neo4j DB and trying to understand what is tx in the following code. I don't see any declaration of tx and will be happy to understand what is it.

from neo4j import GraphDatabase

driver = GraphDatabase.driver("neo4j://localhost:7687", auth=("neo4j", "password"))

def add_friend(tx, name, friend_name):
    tx.run("MERGE (a:Person {name: $name}) "
           "MERGE (a)-[:KNOWS]->(friend:Person {name: $friend_name})",
           name=name, friend_name=friend_name)

def print_friends(tx, name):
    for record in tx.run("MATCH (a:Person)-[:KNOWS]->(friend) WHERE a.name = $name "
                         "RETURN friend.name ORDER BY friend.name", name=name):
        print(record["friend.name"])

with driver.session() as session:
    session.write_transaction(add_friend, "Arthur", "Guinevere")
    session.write_transaction(add_friend, "Arthur", "Lancelot")
    session.write_transaction(add_friend, "Arthur", "Merlin")
    session.read_transaction(print_friends, "Arthur")

driver.close()
1 Answers

If you follow where the functions add_friend and print_friends are called, you will see that it is used in the session.write_transaction() function. This parameter list in the function add_friend tx, name, friend_name is mapped exactly with add_friend, "Arthur", "Guinevere":

 Thus  tx ==> add_friend, name==> Arthur, friend_name==> Guinevere

It leads to your question, what is tx and why add_friend is assigned to tx?

In Java, the function add_friend is a method that references to the current object where it is being called. Thus, tx is current object "session" which the driver (neo4j) created for you to create nodes and do a search for that nodes.

Related