Skip to main content

Simple subclass wrapper around `threading.Thread` to get the return value from a thread in python (from `threading` built-in package in Python Standard library). Exact same interface for creating an instance of this threading sublcass as `threading.Thread`!

Project description

Python API

GitHub license GitHub stars GitHub forks
PyPI version
PyPI - Wheel PyPI - Format PyPI - Status
PyPI - Implementation PyPI - Python Version
codebeat badge

Motivation

I created this package because I needed to store the result of a thread while running tests for the yt_videos_list package and there seemed to be no simple way to get the result from threading.Thread() without importing other modules, creating a Queue, or creating a list and then storing the result in the list, or doing other hacky things.

Sources I looked at before creating the custom class below
Implementation in yt_videos_list

This package is really only 6 lines of code:

import threading

class ThreadWithResult(threading.Thread):
    def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None):
        def function():
            self.result = target(*args, **kwargs)
        super().__init__(group=group, target=function, name=name, daemon=daemon)

The explanation is in the docstrings in the thread_with_result module, and is also accessible through the python interpreter with

python3     # MacOS/Linux
python      # Windows
from save_thread_result import ThreadWithResult
help(ThreadWithResult)
Installing the package

Enter the following in your command line:

# if something isn't working properly, try rerunning this
# the problem may have been fixed with a newer version

pip3 install -U save-thread-result     # MacOS/Linux
pip  install -U save-thread-result     # Windows
Initializing and using the ThreadWithResult class

This package uses a threading.Thread subclass ThreadWithResult that saves the result of a thread (from threading built-in package in the Python Standard library) as its result attribute - i.e. after the thread finishes running, call thread.result to get the return value from the function that ran on that thread.

python3     # MacOS/Linux
python      # Windows
from save_thread_result import ThreadWithResult

# As of Release 0.0.3, you can also specify values for
#`group`, `name`, and `daemon` if you want to set those
# values manually.
thread = ThreadWithResult(
    target = my_function,
    args   = (my_function_arg1, my_function_arg2, ...)
    kwargs = (my_function_kwarg1=kwarg1_value, my_function_kwarg2=kwarg2_value, ...)
)

thread.start()
thread.join()
if getattr(thread, 'result', None):
    print(thread.result)
else:
    # thread.result attribute not set - something caused
    # the thread to terminate BEFORE the thread finished
    # executing the function passed in through the
    # `target` argument
    print('ERROR! Something went wrong while executing this thread, and the function you passed in did NOT complete!!')

To see why checking getattr(thread, 'result', None) might be necessary for a more complicated scenario, see this modification in a testing module from the yt_videos_list package. NOTE that the result attribute was named failed in this commit (the subclass implementation here assigned the result of the threaded function to self.failed instead of to self.result)!

Verified scenario:

Seeing all available methods and attributes for ThreadWithResult class
python3     # MacOS/Linux
python      # Windows
from save_thread_result import ThreadWithResult
help(ThreadWithResult)
Usage Statistics

PyPI - Daily Downloads PyPI - Weekly Downloads PyPI - Monthly Downloads
PePY Weekly Downloads PePY Monthly Downloads PePY Total Downloads

If you found this interesting or useful, please consider starring this repo at GitHub so other people can more easily find and use this. Thanks!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

save-thread-result-0.0.5.tar.gz (14.8 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page