TomographicImaging / eqt

A number of templates and tools to develop Qt GUI's with Python effectively.
Other
2 stars 3 forks source link

Add PrintCallback default #74

Open paskino opened 1 year ago

paskino commented 1 year ago

When using a Worker we suggest to use the following code


def some_function(*args):
    value = some_computation_or_io()
    return value

worker = Worker(some_function, *args)
# tpool is a threadpool
tpool.start(worker)

One could update on the progress of some_function by connecting a suitable update_progress function that handles the int and provides some info to the user. This can be done by connecting the signal as

worker.signals.progress.connect(update_progress)

One should also modify some_function to emit the progress. As explained in the README, it is sufficient to use the function passed as key worded argument, with keyword progress_callback


def some_function(*args, **kwargs):
    progress_update = kwargs.get('progress_callback')
    progress_update.emit(10)
    value = some_computation_or_io()
    progress_update.emit(100)
    return value

The problem here is that progress_callback may not be defined and then calling emit on a NoneType will result in an exception.

I'm suggesting to add some default function to either print or use logging, see https://github.com/TomographicImaging/iDVC/blob/71d314d6f6957cba4d751b79ebea1c51d1079292/src/idvc/dvc_interface.py#L96-L99


class PrintCallback(object):
    '''Class to handle the emit call when no callback is provided'''
    def emit(self, *args, **kwargs):
        print (args, kwargs)

class LoggingCallback(object):
    '''Class to handle the emit call when no callback is provided'''
    def __init__(self, level=logging.INFO)
        self.level = level
    def emit(self, *args, **kwargs):
        # try to give a string representation of args and kwargs
        string = str(args) + " " + str(kwargs)
        logging.log(self.level, string)

def some_function(*args, **kwargs):
    progress_update = kwargs.get('progress_callback', LoggingCallback())
    progress_update.emit(10)
    value = some_computation_or_io()
    progress_update.emit(100)
    return value

In this way we are always sure that progress_update exists and can handle emit.