Add types for arguments, specify docstrings.

This commit is contained in:
zhangrq02 2023-01-06 13:04:20 +08:00
parent 4c61450f13
commit 154bbea709
No known key found for this signature in database
GPG Key ID: 03E6FF68E3E855D1
1 changed files with 18 additions and 6 deletions

View File

@ -1739,8 +1739,13 @@ def all_equal(iterable):
return next(g, True) and not next(g, False)
def is_port_in_use(port, host="localhost"):
"""Check if localhost:port is in use."""
def _is_port_in_use(port: int, host="localhost") -> bool:
"""Check if 'host:port' is in use. Return True if it is, False otherwise.
Keyword arguments:
port -- the port to check
host -- the host to check (default "localhost")
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((host, port))
@ -1751,24 +1756,31 @@ def is_port_in_use(port, host="localhost"):
s.close()
def find_available_port(start, host, auto_select=False):
def find_available_port(start: int, host: str, auto_select=False) -> int:
"""Given a starting port and a host, handle finding a port.
If `auto_select` is False, a busy port will raise an error.
If `auto_select` is True, the next free higher port will be used.
Keyword arguments:
start -- the port to start looking from
host -- the host to find a port on
auto_select -- whether to automatically select a new port if the given port is busy (default False)
RETURNS (int): The port to use.
"""
if not is_port_in_use(start, host):
if not _is_port_in_use(start, host):
return start
port = start
if not auto_select:
raise ValueError(Errors.E1050.format(port=port))
while is_port_in_use(port, host) and port < 65535:
while _is_port_in_use(port, host) and port < 65535:
port += 1
if port == 65535 and is_port_in_use(port, host):
if port == 65535 and _is_port_in_use(port, host):
raise ValueError(Errors.E1049.format(host=host))
# if we get here, the port changed