Handling Shared Resources

Skip to first unread message

xlSlim Dev

Aug 24, 2022, 5:36:24 AM8/24/22
to xlSlim Support

Often your code will need to access a shared resource. Typical examples could be database connections, message broker connections, a trained model and so on. In essence, anything that takes a long time to create and would benefit from being reused.

xlSlim can cache any Python object in memory, including shared resources. The usual way to cache a shared resource in xlSlim is to use a factory function. Let's say we have this shared resource:

class SharedResourceClass:
    """This could be any resource that you would like to share.
    Perhaps because the class is slow to initialise or you want to track usage

    def __init__(self, initial_value: int) -> None:

        self._shared_resource = initial_value

    def access_shared_resource(self) -> int:
        return self._shared_resource

    def update_shared_resource(self, new_value: int) -> None:
        self._shared_resource = new_value

This factory function will create a new instance of the SharedResourceClass:

def create_shared_resource(initial_value: int) -> SharedResourceClass:
    return SharedResourceClass(initial_value)

And these utility functions can be used to read and update the shared object:

def access_shared_resource(sr: SharedResourceClass) -> int:
    return sr.access_shared_resource()

def update_shared_resource(sr: SharedResourceClass, new_value: int) -> str:
    return f"Updated to {new_value}"

This gist has the full code: https://gist.github.com/RusselWebber/98378a015538efaeb7fd9e7927f0f959

In Excel, call the factory function to create the shared resource, and then pass the cache handle to the utility functions.


Please let me know if there are further comments or questions.

Reply all
Reply to author
0 new messages