Typing Stubs for ipaddress
types-ipaddress is a PEP 561 compliant stub-only package providing static type hints for Python's built-in `ipaddress` module. It allows type-checking tools like MyPy, PyCharm, and Pyright to perform static analysis on code that uses `ipaddress` functionality. The package tracks the `ipaddress` stubs within the `typeshed` project and is released upon changes to those stubs. The current version is 1.0.8.
Warnings
- gotcha This package only provides type stubs; the actual runtime functionality comes from Python's built-in `ipaddress` module. You do not import directly from `types_ipaddress` at runtime.
- breaking Type stub versions are managed by the `typeshed` project. While `typeshed` aims for compatibility, updates to `types-ipaddress` might introduce changes that cause type-checking errors if your runtime `ipaddress` (i.e., your Python version) is significantly older or newer than what the stubs were last tested against. `typeshed` policy states 'any version bump can introduce changes that might make your code fail to type check'.
- gotcha Contributions and bug fixes for the `ipaddress` stubs should be made directly to the `python/typeshed` GitHub repository, not to the `types-ipaddress` PyPI project directly.
- deprecated `typeshed` officially dropped Python 2 support for `ipaddress` stubs in March 2022. While older `types-ipaddress` versions might exist, newer stubs will not support Python 2 type checking.
Install
-
pip install types-ipaddress
Imports
- ip_address
from ipaddress import ip_address
- ip_network
from ipaddress import ip_network
- IPv4Address
from ipaddress import IPv4Address
- IPv6Address
from ipaddress import IPv6Address
- IPv4Network
from ipaddress import IPv4Network
- IPv6Network
from ipaddress import IPv6Network
Quickstart
import ipaddress
def check_ip_in_network(ip_str: str, network_str: str) -> bool:
try:
ip_addr = ipaddress.ip_address(ip_str)
network = ipaddress.ip_network(network_str, strict=False)
return ip_addr in network
except ValueError as e:
print(f"Error: {e}")
return False
if __name__ == "__main__":
test_ip_v4 = "192.168.1.5"
test_network_v4 = "192.168.1.0/24"
print(f"Is {test_ip_v4} in {test_network_v4}? {check_ip_in_network(test_ip_v4, test_network_v4)}")
test_ip_v6 = "2001:db8::1"
test_network_v6 = "2001:db8::/64"
print(f"Is {test_ip_v6} in {test_network_v6}? {check_ip_in_network(test_ip_v6, test_network_v6)}")
invalid_ip = "999.999.999.999"
valid_network = "10.0.0.0/8"
print(f"Is {invalid_ip} in {valid_network}? {check_ip_in_network(invalid_ip, valid_network)}")