user972014
user972014

Reputation: 3856

Python3 - Asynchronously initialize a member

My class has a member that can be generated after a long calculation. This member is not "necessary" for the functionality of the program, and I want it to be generated in some other thread or something similar

(In my case it probably must be in the same process since it initializes some OS related stuff that must happen on the same process)

This functionality can be used like this:

def generate_object():
    # VERY LARGE CALCULATION INCLUDING READING FILES AND BUILDING SOME DATA STRUCTURE
    return created_object

class MyClass:
    def __init__(self):
        self.__some_member = asyncly generate_object()

    def func(self):
        if self.__some_member is already initialized:
            print(self.__some_member.some_func())
        print("functioning normally without member")

Upvotes: 0

Views: 55

Answers (1)

user4815162342
user4815162342

Reputation: 155046

This is a good use case for concurrent futures.

import concurrent.futures

executor = concurrent.futures.ThreadPoolExecutor()

def generate_object():
    ...
    return created_object

class MyClass:
    def __init__(self):
        self.__some_member = executor.submit(generate_object)

    def func(self):
        if self.__some_member.done():
            print(self.__some_member.result().some_func())
        print("functioning normally without member")

ThreadPoolExecutor.submit returns a Future object that represents a value that might not yet be available. You can test whether it the future is complete using the done(), and access the result (the object returned by generate_object) using result(). Calling result() on a future that is not done blocks the thread until the result is available. (But you can also specify a timeout.)

Upvotes: 1

Related Questions