Skip to content

Commit 6b8131e

Browse files
committed
Converted 'pick_local_ip_address' function to use generics.
1 parent 343f343 commit 6b8131e

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

pytcp/lib/ip_helper.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -35,20 +35,22 @@
3535

3636
from __future__ import annotations
3737

38-
from typing import TYPE_CHECKING, cast
38+
from typing import TYPE_CHECKING, TypeVar, cast
3939

4040
from net_addr import (
4141
Ip4Address,
4242
Ip4AddressFormatError,
4343
Ip6Address,
4444
Ip6AddressFormatError,
4545
)
46+
from net_addr import IpAddress
4647
from pytcp import stack
4748

4849
if TYPE_CHECKING:
49-
from net_addr import IpAddress
5050
from pytcp.socket.socket import AddressFamily, SocketType
5151

52+
T = TypeVar("T", bound=IpAddress)
53+
5254

5355
EPHEMERAL_PORT_RANGE = range(32168, 60700, 2)
5456

@@ -85,20 +87,19 @@ def str_to_ip(
8587
return None
8688

8789

88-
def pick_local_ip_address(
89-
remote_ip_address: IpAddress,
90-
) -> Ip6Address | Ip4Address:
90+
def pick_local_ip_address(remote_ip_address: T) -> T:
9191
"""
9292
Pick appropriate source IP address based on provided
9393
destination IP address.
9494
"""
9595

96-
assert isinstance(remote_ip_address, (Ip6Address, Ip4Address))
97-
9896
if isinstance(remote_ip_address, Ip6Address):
9997
return pick_local_ip6_address(remote_ip_address)
10098

101-
return pick_local_ip4_address(remote_ip_address)
99+
if isinstance(remote_ip_address, Ip4Address):
100+
return pick_local_ip4_address(remote_ip_address)
101+
102+
raise TypeError(f"Unsupported IP address type: {type(remote_ip_address)}")
102103

103104

104105
def pick_local_ip6_address(

0 commit comments

Comments
 (0)