You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+86-1Lines changed: 86 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -25,7 +25,6 @@ import pydantic
25
25
classModel(pydantic.BaseModel):
26
26
address: pydantic.IPvAnyAddress
27
27
28
-
29
28
m = Model(address="1.2.3.4")
30
29
print(type(m.address))
31
30
print(m.model_dump_json())
@@ -131,10 +130,96 @@ The validation relies mostly on `netaddr` objects constructors. There's currentl
131
130
132
131
### Additionnal features
133
132
133
+
## IPAny
134
+
134
135
That may not be much, but an `IPAny` type is available. `pydantic` should produce the most acccurate object depending of the source object. An `IPAny` field will produce
135
136
136
137
* an `IPSet` if provided type is `list`, `tuple` or `set`
137
138
* an `IPNetwork` if value is a CIDR `str`
138
139
* an `IPRange` if value is an `str` containing a `-` character
139
140
* an `IPGlob` if value is an `str` containing a `*` char.
140
141
* an `IPAddress` in other cases.
142
+
143
+
## `IPv4Address` / `IPv6Address`
144
+
145
+
In case you want to match only IPv4 or IPv6 addresses (although, for portability, I suggest you don't), you can use these Internet Protocol version specific types annotations.
146
+
147
+
For instance, the following code:
148
+
149
+
```python
150
+
import pydantic
151
+
import netaddr_pydantic
152
+
153
+
classModel(pydantic.BaseModel):
154
+
address: netaddr_pydantic.IPv4Address
155
+
156
+
m4 = Model(address="1.2.3.4")
157
+
print(f"IPv4 has been validated: {m4.address}")
158
+
159
+
try:
160
+
m6 = Model(address="dead:b00b:cafe::1")
161
+
except pydantic.ValidationError:
162
+
print("IPv6 address did not pass:")
163
+
raise
164
+
```
165
+
166
+
Produces the following:
167
+
168
+
```
169
+
IPv4 has been validated: 1.2.3.4
170
+
IPv6 address did not pass:
171
+
Traceback (most recent call last):
172
+
File "t.py", line 11, in <module>
173
+
m6 = Model(address="dead:b00b:cafe::1")
174
+
File "/env/lib/python3.13/site-packages/pydantic/main.py", line 253, in __init__
0 commit comments