0

Background

I've written a state machine as shown below following these docs.

States are implemented an shown.

## Base Class.
class State:
    def __init__(self,host='10.90.51.177'):
      self.host = host
      self.s = winrm.Session(host, auth=('user', 'pass'))
      self.grpc_channel = grpc.insecure_channel(f"{host}:50051")
      self.stub = my_grpc_lib.MyServiceStub(self.grpc_channel)
class Connecting(State):
    def run(self):
      # calls using winrm session
      self.s.do_thing()
      # calls using gprc_channel
      self.stub.do_thing()
    def next(self):
      return Ready(self.host)
class Ready(State):
    def next(self):
      print('In State Ready')

The State Machine is implemented as shown.

class GameStateMachine:
  def start(host):
    state = Connecting(host=host)
    while str(state) != "Ready":
      print(f"[StateMachine] - Entering state {state}")
      state.run()
      state = state.next()
    state = state.next()

I ultimately loop the below snippet 1000 times in a run.py

GameStateMachine.start(host="192.168.2.4")

Questions..

The main question I have is this... When are the session objects garbage collected? Am I creating thousands of sessions that lay around holding sockets open?

And this leads me to a few more questions...

  • Am I re-creating multiple sessions every time I return (and thus instantiate) a State object, or are they cleaned up by some external garbage collection?
  • How can I use a debugger properly to get an idea of how many objects or sessions I have in the stack? I've had difficulty showing a full "object stack" to troubleshoot this myself.

Ultimately, Would it be better for me to instantiate the grpc_channel and winrm session outside my state machine?

1 Answer 1

1

Python objects have a method __del__ that is called when an object is being garbage collected. You can use it to determine when an object is being deleted.

As a general rule, if an object uses an external resource (file, database, socket, etc.), it is usually best to close that resource explicitly if you can.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.