Adding additional attributes
  • 14 Jan 2022
  • 1 Minute to read
  • Contributors
  • Dark
    Light
  • PDF

Adding additional attributes

  • Dark
    Light
  • PDF

Article summary

You may add additional attributes to the Context object. The same Context object is passed to every execution of your function within it's Node, and will persist until the Node itself is removed from memory.

Adding additional attributes allows you to enhance the performance of your function in the case where some expensive process must be performed, but it only needs to be performed once and then used by the rest of your function executions.

For example, establishing a database connection with a PostgreSQL database in your datacenter is expensive, but once accomplished can be used over and over again. To do this, you would, using a processor function:

def processor(*, context, message, source, **kwargs):
    
    # check
    if not hasattr(context, "dbConnection"):
        # lock
        with context:
            # check again
            if not hasattr(context, "dbConnection"):
                # create db connection
                db_connection = ...
                setattr(context, "dbConnection", db_connection)

    # use the db connection for something
    context.dbConnection.execute(...)
    
    return message