Threading
Formify implements a few helper functions to move expensive calculations outside the Ui thread:
formify.tools.BackgroundMethod
Bases: Thread
A wrapper to execute a function in a background thread.
Usage:
import time
@formify.tools.BackgroundMethod
def expensive_calculation(text):
time.sleep(1)
print(text)
expensive_calculation("1")
expensive_calculation("2")
expensive_calculation("3")
print("Hello") # will be printed first
Output:
__init__(target, lazy=None, cleanup=None)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target |
typing.Callable
|
Target method (is executed, when the BackgroundMethod instance is called) |
required |
lazy |
bool
|
A call is skipped, if a newer one is queued. |
None
|
cleanup |
typing.Callable
|
Runs after the target, if provided. |
None
|
Returns:
Name | Type | Description |
---|---|---|
BakgroundMethod |
typing.Callable
|
A callable thread, that executes the target with Callable. If a cleanup is provided, this runs afterwards. |
__call__(*args, **kwargs)
Executes the self.target with the provided args and *kwargs.
formify.tools.LazyBackgroundMethod
Bases: BackgroundMethod
Executes only the latest call. Helpful for updating a plot and wherever else you are only interested in the latest result.
Usage:
import time
@formify.tools.LazyBackgroundMethod
def expensive_calculation(text):
time.sleep(1)
print(text)
expensive_calculation("1")
expensive_calculation("2") # will not be executed!
expensive_calculation("3")
print("Hello")
Output:
formify.tools.do_in_ui_thread(func)
Immediately executes func
in the main thread (UI thread). Useful when interacting with UI elements.
Usage:
textarea = formify.ControlTextarea("Output")
@formify.tools.BackgroundMethod
def expensive_calculation(text):
time.sleep(1)
def output_text():
textarea.value += text + "\n"
do_in_ui_thread(output_text)
expensive_calculation(1)
expensive_calculation(2)
expensive_calculation(3)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
func |
typing.Callable
|
fucntion to be called (without any arguments) |
required |