ResourceWarning from Socket creation

Hey together,

In file gamspy._container.py method open_connection sometimes when gamspy is failing to create a connection to the socket for a while (in my case due to a library import, did not figure out why yet), when the connection fails, the socket is never closed and python returns thousands of resource warnings.

ResourceWarning: Enable tracemalloc to get the object allocation traceback
/opt/homebrew/Caskroom/miniconda/base/envs/repair-env/lib/python3.12/site-packages/gamspy/_container.py:107: ResourceWarning: unclosed <socket.socket fd=5, family=2, type=1, proto=0, laddr=('127.0.0.1', 57975)>
  new_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

The following code snippet is from file gamspy._container.py lines 101 to 118.
In my opinion, the problem can be resolved by closing the socket after a connection has failed by adding new_socket.close() after except (ConnectionRefusedError, OSError) as e:

start = time.time()
    while True:
        if process.poll() is not None:
            raise ValidationError(process.communicate()[0])

        try:
            new_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            new_socket.connect(address)
            break
        except (ConnectionRefusedError, OSError) as e:
            end = time.time()

            if end - start > TIMEOUT:
                raise GamspyException(
                    f"Timeout while establishing the connection with socket. {process.communicate()[0]}"
                ) from e

    return new_socket, process

GAMSPy version

GAMSPy version: 1.0.1
GAMS version: 47.6.0
gamspy_base version: 47.6.0

Hi Jannick,

We cannot close a connection that was never actualized. If you don’t want to see this warning, you can do the following at the beginning of your script:

import warnings

warnings.simplefilter("ignore", ResourceWarning)