Search code examples
pythonclassplotlyinitfigure

passing args to threading.Thread to a CLASS without override class self?


Pretty sure that this should be a simple noob thing or a conceptual confusion of mine but I am not seeing it. Context: I need to do several focused plotly figures from a HUGE figure (used as base figure) and save it on separate html files. So I planned to load de huge figure just once in a class init and then thread args to a second class function that makes the work of setting limits and saving fig to html.

In theory (I guess) everything should be fine but when a pass the args to the target thread the first argument passed overrides the self local var of class that contains the huge figure to cut. So, how do I have to pass the args to avoid this overriding issue???. Any suggestions??. Simplified example:

´´´ import threading

 class Map ():
  def __init__(self):
         self.fig = load('HugeFig')

 def second (self,arg1,arg2):
         self.fig.show()            %here I set limit but show() exemplifies
                                    %the issue that is reading the '_' from thread args. I 
                                     %thought use self to access self.fig but error : str has no fig 

class Main ():
  def run () :
     Map()                                              % calls the class to load HUGE figure only once.

     threat = threading.Thread(target=Map.second,args=(_,arg1,arg2))

if __name__ == "__main__":

     Main.run()

´´´


Solution

  • You simply use class in wrong way.

    You have to assign object/instance to variable my_map = Map()
    and later use this variable target=my_map.second instead of target=Map.second.

    And use args without _ - it will automatically assign my_map to self

    def run () :
        my_map = Map()
    
        threat = threading.Thread(target=my_map.second, args=(arg1, arg2))