Do I need to call Channel.close() when my process exits?

Viewed 270

I am using gRPC in a Python script, and most of my code is wrapped in this:

def main():
    with grpc.insecure_channel(address) as channel:
        ...

I am trying to reduce the indentation depth of the code, and wondering if we can drop the with. (One can argue if this is just vanity, or useful because it becomes more readable, but let's go with it for a second. I'm just curious about the behavior of gRPC here.) I would replace it with an explicit call to .close, however this script is likely to be stopped with Ctrl+C most of the time so that wouldn't get called.

How bad is it if the channel doesn't get closed? My process is exiting anyway, so it won't leak memory. Will it clog a connection slot on the server? For how long? This script is going to be called rarely, manually, and not multiple instances at the same time.

1 Answers

Your Operating System should close connections when the process is killed, and otherwise there are configurable timeouts/deadlines that are generally wise to use, so it's unlikely that you'll leak resources. It's not recommended to exit without closing the channel, however.

One solution to your nesting problem would be to extract your code into a separate function:

def do_work(channel):
  pass

def main():
  with grpc.insecure_channel(address) as channel:
    do_work(channel)
Related