3

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!

MisterPresident
  • 563
  • 7
  • 20

3 Answers3

3

_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.

Community
  • 1
  • 1
pilcrow
  • 56,591
  • 13
  • 94
  • 135
1

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)
Srini
  • 1,626
  • 2
  • 15
  • 25
ZdaR
  • 22,343
  • 7
  • 66
  • 87
  • I tried that but: AttributeError: 'Thread' object has no attribute '_Thread__arg' – MisterPresident Jun 15 '15 at 17:28
  • I ran this piece of code on my Python2.7 and it is giving expected output. – ZdaR Jun 15 '15 at 17:37
  • Holy Crap?! I did a copy and pase three times... print sys.version_info gives me: sys.version_info(major=2, minor=7, micro=6, releaselevel='final', serial=0) – MisterPresident Jun 15 '15 at 17:41
  • Yes it's almost as if variables starting with `_` were private implementation details! (Heck this one even starts with `__`). – Voo Jun 16 '15 at 13:09
0

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!

MisterPresident
  • 563
  • 7
  • 20