1

I've been reading about weak and strong references in Python, specifically regarding errors that look like

ReferenceError: weakly-referenced object no longer exists

Here I have a basic RPC interface that passes objects from client to server, where the server then saves those objects into a predefined class. Here's a basic outline of all the structures in my code. Note the behavior of "flags":

Client side:

# target = 'file.txt', flags = [(tuple, tuple), (tuple, tuple)]
def file_reminder(self, flags, target):         
    target = os.path.abspath(target)          
    c = rpyc.connect("localhost", port)        
    # flags can be referenced here
    return c.root.file_reminder(flags, target)  

Server side:

class MyService(rpyc.Service):
     jobs = EventLoop().start()

      # this is what's called from the client side
      def exposed_file_reminder(self, flags, target):
           reminder = FileReminder(flags, target)
           self.jobs.add_reminder(reminder)
           # reminder.flags can be referenced here
           return "Added a new reminder"

class FileReminder(object):
     def __init__(self, flags, target):
         self.flags = flags
         self.target = target

     def __str__(self):
         return str(self.flags) + target

class EventLoop(threading.Thread):
     def __init__(self):
         self.reminders = []

     def add_reminder(self, reminder):
         # reminder.flags can be referenced here
         self.reminders.append(reminder)

     def run(self):
         while True:
             for reminder in self.reminders:
                  # reminder.flags is no longer defined here
                  print reminder

The issue here is the "flags" argument always throwing a ReferenceError when printed in the thread (or manipulated in any way within the Thread's run() function). Note, target is processed just fine. When I change "flags" to an immutable, like a string, no ReferenceError is popping up. This is making my head scratch so any help would be appreciated!

danfang
  • 11
  • 1
  • 3

1 Answers1

0

Using Python GC on Compound Objects, I was able to fix this, although I do not know if it was done using "best practices".

Here's what I think the error was: although there were many references to the list itself, there were no explicit references to the tuples within that list. What I did to fix it was create a deep copy of the list on the instantiation of a FileReminder

For example

def __init__(self, flags, target):
    self.flags = []
    for flag in flags:
        flags.append(flag)

This seems to work!

Community
  • 1
  • 1
danfang
  • 11
  • 1
  • 3