Get Arguments of Thread Variable

308 Views Asked by At

I have a very simple question:

myThread = Thread(target=TestTarget, args=(1, Event(),))

Is it possible to get the arguments just using the Variable myThread?

Thank you!

3

There are 3 best solutions below

0
On BEST ANSWER

After pilcrows answer - i use this working solution:

from threading import Thread

class myThread(Thread):

    args = None

    def __init__(self, group=None, target=None, args=(), name=None, kwargs = None, daemon = None):
        self.args = args
        super(RaThread, self).__init__(group=group, target=target, args=args, name=name, kwargs=kwargs, daemon=daemon)

Thank you all for helping!

4
On

You may simply use _Thread__arg on a Thread object to get the details of the arguments passed to that Thread object.

import threading

def TestTarget(a, b):
    pass

myThread = threading.Thread(target=TestTarget, args=(1, 2,))

print myThread._Thread__arg

>>> (1, 2)
0
On

_Thread__args and _Thread__kwargs store the constructor's arguments.

However, as you might guess by the underscores, these are not part of the public API. Indeed, "mangled, renamed attributes" are intended to discourage direct access.

Additionally, these attributes are specific to the CPython implementation. Jython, for example, appears not to expose these attributes by those names (disclaimer: I did not test, instead just glanced at the source).

In your case, it would perhaps be better to store the arguments in some application-meaningful way in a subclass of Thread, and access those.