Ravenveil commited on
Commit
3d8cdb8
·
verified ·
1 Parent(s): 7589854

backup 04_physworld 2026-11-08 10:11:26 (part 7)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +46 -0
  2. physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/__pycache__/readers.cpython-311.pyc +0 -0
  3. physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/__pycache__/simple.cpython-311.pyc +0 -0
  4. physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/_adapters.py +170 -0
  5. physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/_common.py +107 -0
  6. physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/_itertools.py +35 -0
  7. physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/_legacy.py +121 -0
  8. physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/abc.py +151 -0
  9. physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/readers.py +122 -0
  10. physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/simple.py +125 -0
  11. physworld_p1_20261018/envs/p1/lib/python3.11/importlib/simple.py +14 -0
  12. physworld_p1_20261018/envs/p1/lib/python3.11/importlib/util.py +322 -0
  13. physworld_p1_20261018/envs/p1/lib/python3.11/inspect.py +0 -0
  14. physworld_p1_20261018/envs/p1/lib/python3.11/io.py +115 -0
  15. physworld_p1_20261018/envs/p1/lib/python3.11/ipaddress.py +2430 -0
  16. physworld_p1_20261018/envs/p1/lib/python3.11/json/__init__.py +359 -0
  17. physworld_p1_20261018/envs/p1/lib/python3.11/json/__pycache__/__init__.cpython-311.pyc +0 -0
  18. physworld_p1_20261018/envs/p1/lib/python3.11/json/__pycache__/decoder.cpython-311.pyc +0 -0
  19. physworld_p1_20261018/envs/p1/lib/python3.11/json/__pycache__/encoder.cpython-311.pyc +0 -0
  20. physworld_p1_20261018/envs/p1/lib/python3.11/json/__pycache__/scanner.cpython-311.pyc +0 -0
  21. physworld_p1_20261018/envs/p1/lib/python3.11/json/__pycache__/tool.cpython-311.pyc +0 -0
  22. physworld_p1_20261018/envs/p1/lib/python3.11/json/decoder.py +356 -0
  23. physworld_p1_20261018/envs/p1/lib/python3.11/json/encoder.py +443 -0
  24. physworld_p1_20261018/envs/p1/lib/python3.11/json/scanner.py +73 -0
  25. physworld_p1_20261018/envs/p1/lib/python3.11/json/tool.py +85 -0
  26. physworld_p1_20261018/envs/p1/lib/python3.11/keyword.py +63 -0
  27. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_asyncio.cpython-311-x86_64-linux-gnu.so +3 -0
  28. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_bisect.cpython-311-x86_64-linux-gnu.so +0 -0
  29. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_blake2.cpython-311-x86_64-linux-gnu.so +3 -0
  30. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_bz2.cpython-311-x86_64-linux-gnu.so +0 -0
  31. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_codecs_cn.cpython-311-x86_64-linux-gnu.so +3 -0
  32. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_codecs_hk.cpython-311-x86_64-linux-gnu.so +3 -0
  33. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_codecs_iso2022.cpython-311-x86_64-linux-gnu.so +0 -0
  34. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_codecs_jp.cpython-311-x86_64-linux-gnu.so +3 -0
  35. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_codecs_kr.cpython-311-x86_64-linux-gnu.so +3 -0
  36. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_codecs_tw.cpython-311-x86_64-linux-gnu.so +3 -0
  37. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_contextvars.cpython-311-x86_64-linux-gnu.so +0 -0
  38. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_crypt.cpython-311-x86_64-linux-gnu.so +0 -0
  39. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_csv.cpython-311-x86_64-linux-gnu.so +3 -0
  40. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_ctypes.cpython-311-x86_64-linux-gnu.so +3 -0
  41. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_ctypes_test.cpython-311-x86_64-linux-gnu.so +0 -0
  42. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_curses.cpython-311-x86_64-linux-gnu.so +3 -0
  43. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_curses_panel.cpython-311-x86_64-linux-gnu.so +0 -0
  44. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_datetime.cpython-311-x86_64-linux-gnu.so +3 -0
  45. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_decimal.cpython-311-x86_64-linux-gnu.so +3 -0
  46. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_elementtree.cpython-311-x86_64-linux-gnu.so +3 -0
  47. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_hashlib.cpython-311-x86_64-linux-gnu.so +3 -0
  48. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_heapq.cpython-311-x86_64-linux-gnu.so +3 -0
  49. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_json.cpython-311-x86_64-linux-gnu.so +3 -0
  50. physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_lsprof.cpython-311-x86_64-linux-gnu.so +3 -0
.gitattributes CHANGED
@@ -3423,3 +3423,49 @@ physworld_p1_20261018/envs/p1/lib/python3.11/email/__pycache__/_header_value_par
3423
  physworld_p1_20261018/envs/p1/lib/python3.11/ensurepip/_bundled/pip-24.0-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text
3424
  physworld_p1_20261018/envs/p1/lib/python3.11/ensurepip/_bundled/setuptools-79.0.1-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text
3425
  physworld_p1_20261018/envs/p1/lib/python3.11/idlelib/__pycache__/configdialog.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3423
  physworld_p1_20261018/envs/p1/lib/python3.11/ensurepip/_bundled/pip-24.0-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text
3424
  physworld_p1_20261018/envs/p1/lib/python3.11/ensurepip/_bundled/setuptools-79.0.1-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text
3425
  physworld_p1_20261018/envs/p1/lib/python3.11/idlelib/__pycache__/configdialog.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3426
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_asyncio.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3427
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_blake2.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3428
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_codecs_cn.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3429
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_codecs_hk.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3430
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_codecs_jp.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3431
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_codecs_kr.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3432
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_codecs_tw.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3433
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_csv.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3434
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_ctypes.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3435
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_curses.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3436
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_datetime.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3437
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_decimal.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3438
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_elementtree.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3439
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_hashlib.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3440
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_heapq.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3441
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_json.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3442
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_lsprof.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3443
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_lzma.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3444
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_multibytecodec.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3445
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_pickle.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3446
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_socket.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3447
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_sqlite3.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3448
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_ssl.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3449
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_struct.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3450
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_testbuffer.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3451
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_testcapi.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3452
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_testclinic.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3453
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_testinternalcapi.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3454
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_tkinter.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3455
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_xxsubinterpreters.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3456
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_zoneinfo.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3457
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/array.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3458
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/audioop.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3459
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/binascii.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3460
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/cmath.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3461
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/math.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3462
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/pyexpat.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3463
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/readline.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3464
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/select.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3465
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/unicodedata.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3466
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/zlib.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3467
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib2to3/tests/__pycache__/test_fixers.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3468
+ physworld_p1_20261018/envs/p1/lib/python3.11/lib2to3/tests/data/__pycache__/infinite_recursion.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3469
+ physworld_p1_20261018/envs/p1/lib/python3.11/pydoc_data/__pycache__/topics.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3470
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/PIL/__pycache__/Image.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3471
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/PIL/__pycache__/TiffImagePlugin.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/__pycache__/readers.cpython-311.pyc ADDED
Binary file (8.55 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/__pycache__/simple.cpython-311.pyc ADDED
Binary file (7.13 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/_adapters.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import suppress
2
+ from io import TextIOWrapper
3
+
4
+ from . import abc
5
+
6
+
7
+ class SpecLoaderAdapter:
8
+ """
9
+ Adapt a package spec to adapt the underlying loader.
10
+ """
11
+
12
+ def __init__(self, spec, adapter=lambda spec: spec.loader):
13
+ self.spec = spec
14
+ self.loader = adapter(spec)
15
+
16
+ def __getattr__(self, name):
17
+ return getattr(self.spec, name)
18
+
19
+
20
+ class TraversableResourcesLoader:
21
+ """
22
+ Adapt a loader to provide TraversableResources.
23
+ """
24
+
25
+ def __init__(self, spec):
26
+ self.spec = spec
27
+
28
+ def get_resource_reader(self, name):
29
+ return CompatibilityFiles(self.spec)._native()
30
+
31
+
32
+ def _io_wrapper(file, mode='r', *args, **kwargs):
33
+ if mode == 'r':
34
+ return TextIOWrapper(file, *args, **kwargs)
35
+ elif mode == 'rb':
36
+ return file
37
+ raise ValueError(
38
+ "Invalid mode value '{}', only 'r' and 'rb' are supported".format(mode)
39
+ )
40
+
41
+
42
+ class CompatibilityFiles:
43
+ """
44
+ Adapter for an existing or non-existent resource reader
45
+ to provide a compatibility .files().
46
+ """
47
+
48
+ class SpecPath(abc.Traversable):
49
+ """
50
+ Path tied to a module spec.
51
+ Can be read and exposes the resource reader children.
52
+ """
53
+
54
+ def __init__(self, spec, reader):
55
+ self._spec = spec
56
+ self._reader = reader
57
+
58
+ def iterdir(self):
59
+ if not self._reader:
60
+ return iter(())
61
+ return iter(
62
+ CompatibilityFiles.ChildPath(self._reader, path)
63
+ for path in self._reader.contents()
64
+ )
65
+
66
+ def is_file(self):
67
+ return False
68
+
69
+ is_dir = is_file
70
+
71
+ def joinpath(self, other):
72
+ if not self._reader:
73
+ return CompatibilityFiles.OrphanPath(other)
74
+ return CompatibilityFiles.ChildPath(self._reader, other)
75
+
76
+ @property
77
+ def name(self):
78
+ return self._spec.name
79
+
80
+ def open(self, mode='r', *args, **kwargs):
81
+ return _io_wrapper(self._reader.open_resource(None), mode, *args, **kwargs)
82
+
83
+ class ChildPath(abc.Traversable):
84
+ """
85
+ Path tied to a resource reader child.
86
+ Can be read but doesn't expose any meaningful children.
87
+ """
88
+
89
+ def __init__(self, reader, name):
90
+ self._reader = reader
91
+ self._name = name
92
+
93
+ def iterdir(self):
94
+ return iter(())
95
+
96
+ def is_file(self):
97
+ return self._reader.is_resource(self.name)
98
+
99
+ def is_dir(self):
100
+ return not self.is_file()
101
+
102
+ def joinpath(self, other):
103
+ return CompatibilityFiles.OrphanPath(self.name, other)
104
+
105
+ @property
106
+ def name(self):
107
+ return self._name
108
+
109
+ def open(self, mode='r', *args, **kwargs):
110
+ return _io_wrapper(
111
+ self._reader.open_resource(self.name), mode, *args, **kwargs
112
+ )
113
+
114
+ class OrphanPath(abc.Traversable):
115
+ """
116
+ Orphan path, not tied to a module spec or resource reader.
117
+ Can't be read and doesn't expose any meaningful children.
118
+ """
119
+
120
+ def __init__(self, *path_parts):
121
+ if len(path_parts) < 1:
122
+ raise ValueError('Need at least one path part to construct a path')
123
+ self._path = path_parts
124
+
125
+ def iterdir(self):
126
+ return iter(())
127
+
128
+ def is_file(self):
129
+ return False
130
+
131
+ is_dir = is_file
132
+
133
+ def joinpath(self, other):
134
+ return CompatibilityFiles.OrphanPath(*self._path, other)
135
+
136
+ @property
137
+ def name(self):
138
+ return self._path[-1]
139
+
140
+ def open(self, mode='r', *args, **kwargs):
141
+ raise FileNotFoundError("Can't open orphan path")
142
+
143
+ def __init__(self, spec):
144
+ self.spec = spec
145
+
146
+ @property
147
+ def _reader(self):
148
+ with suppress(AttributeError):
149
+ return self.spec.loader.get_resource_reader(self.spec.name)
150
+
151
+ def _native(self):
152
+ """
153
+ Return the native reader if it supports files().
154
+ """
155
+ reader = self._reader
156
+ return reader if hasattr(reader, 'files') else self
157
+
158
+ def __getattr__(self, attr):
159
+ return getattr(self._reader, attr)
160
+
161
+ def files(self):
162
+ return CompatibilityFiles.SpecPath(self.spec, self._reader)
163
+
164
+
165
+ def wrap_spec(package):
166
+ """
167
+ Construct a package spec with traversable compatibility
168
+ on the spec/loader/reader.
169
+ """
170
+ return SpecLoaderAdapter(package.__spec__, TraversableResourcesLoader)
physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/_common.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pathlib
3
+ import tempfile
4
+ import functools
5
+ import contextlib
6
+ import types
7
+ import importlib
8
+
9
+ from typing import Union, Optional
10
+ from .abc import ResourceReader, Traversable
11
+
12
+ from ._adapters import wrap_spec
13
+
14
+ Package = Union[types.ModuleType, str]
15
+
16
+
17
+ def files(package):
18
+ # type: (Package) -> Traversable
19
+ """
20
+ Get a Traversable resource from a package
21
+ """
22
+ return from_package(get_package(package))
23
+
24
+
25
+ def get_resource_reader(package):
26
+ # type: (types.ModuleType) -> Optional[ResourceReader]
27
+ """
28
+ Return the package's loader if it's a ResourceReader.
29
+ """
30
+ # We can't use
31
+ # a issubclass() check here because apparently abc.'s __subclasscheck__()
32
+ # hook wants to create a weak reference to the object, but
33
+ # zipimport.zipimporter does not support weak references, resulting in a
34
+ # TypeError. That seems terrible.
35
+ spec = package.__spec__
36
+ reader = getattr(spec.loader, 'get_resource_reader', None) # type: ignore
37
+ if reader is None:
38
+ return None
39
+ return reader(spec.name) # type: ignore
40
+
41
+
42
+ def resolve(cand):
43
+ # type: (Package) -> types.ModuleType
44
+ return cand if isinstance(cand, types.ModuleType) else importlib.import_module(cand)
45
+
46
+
47
+ def get_package(package):
48
+ # type: (Package) -> types.ModuleType
49
+ """Take a package name or module object and return the module.
50
+
51
+ Raise an exception if the resolved module is not a package.
52
+ """
53
+ resolved = resolve(package)
54
+ if wrap_spec(resolved).submodule_search_locations is None:
55
+ raise TypeError(f'{package!r} is not a package')
56
+ return resolved
57
+
58
+
59
+ def from_package(package):
60
+ """
61
+ Return a Traversable object for the given package.
62
+
63
+ """
64
+ spec = wrap_spec(package)
65
+ reader = spec.loader.get_resource_reader(spec.name)
66
+ return reader.files()
67
+
68
+
69
+ @contextlib.contextmanager
70
+ def _tempfile(reader, suffix='',
71
+ # gh-93353: Keep a reference to call os.remove() in late Python
72
+ # finalization.
73
+ *, _os_remove=os.remove):
74
+ # Not using tempfile.NamedTemporaryFile as it leads to deeper 'try'
75
+ # blocks due to the need to close the temporary file to work on Windows
76
+ # properly.
77
+ fd, raw_path = tempfile.mkstemp(suffix=suffix)
78
+ try:
79
+ try:
80
+ os.write(fd, reader())
81
+ finally:
82
+ os.close(fd)
83
+ del reader
84
+ yield pathlib.Path(raw_path)
85
+ finally:
86
+ try:
87
+ _os_remove(raw_path)
88
+ except FileNotFoundError:
89
+ pass
90
+
91
+
92
+ @functools.singledispatch
93
+ def as_file(path):
94
+ """
95
+ Given a Traversable object, return that object as a
96
+ path on the local file system in a context manager.
97
+ """
98
+ return _tempfile(path.read_bytes, suffix=path.name)
99
+
100
+
101
+ @as_file.register(pathlib.Path)
102
+ @contextlib.contextmanager
103
+ def _(path):
104
+ """
105
+ Degenerate behavior for pathlib.Path objects.
106
+ """
107
+ yield path
physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/_itertools.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import filterfalse
2
+
3
+ from typing import (
4
+ Callable,
5
+ Iterable,
6
+ Iterator,
7
+ Optional,
8
+ Set,
9
+ TypeVar,
10
+ Union,
11
+ )
12
+
13
+ # Type and type variable definitions
14
+ _T = TypeVar('_T')
15
+ _U = TypeVar('_U')
16
+
17
+
18
+ def unique_everseen(
19
+ iterable: Iterable[_T], key: Optional[Callable[[_T], _U]] = None
20
+ ) -> Iterator[_T]:
21
+ "List unique elements, preserving order. Remember all elements ever seen."
22
+ # unique_everseen('AAAABBBCCDAABBB') --> A B C D
23
+ # unique_everseen('ABBCcAD', str.lower) --> A B C D
24
+ seen: Set[Union[_T, _U]] = set()
25
+ seen_add = seen.add
26
+ if key is None:
27
+ for element in filterfalse(seen.__contains__, iterable):
28
+ seen_add(element)
29
+ yield element
30
+ else:
31
+ for element in iterable:
32
+ k = key(element)
33
+ if k not in seen:
34
+ seen_add(k)
35
+ yield element
physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/_legacy.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import os
3
+ import pathlib
4
+ import types
5
+ import warnings
6
+
7
+ from typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any
8
+
9
+ from . import _common
10
+
11
+ Package = Union[types.ModuleType, str]
12
+ Resource = str
13
+
14
+
15
+ def deprecated(func):
16
+ @functools.wraps(func)
17
+ def wrapper(*args, **kwargs):
18
+ warnings.warn(
19
+ f"{func.__name__} is deprecated. Use files() instead. "
20
+ "Refer to https://importlib-resources.readthedocs.io"
21
+ "/en/latest/using.html#migrating-from-legacy for migration advice.",
22
+ DeprecationWarning,
23
+ stacklevel=2,
24
+ )
25
+ return func(*args, **kwargs)
26
+
27
+ return wrapper
28
+
29
+
30
+ def normalize_path(path):
31
+ # type: (Any) -> str
32
+ """Normalize a path by ensuring it is a string.
33
+
34
+ If the resulting string contains path separators, an exception is raised.
35
+ """
36
+ str_path = str(path)
37
+ parent, file_name = os.path.split(str_path)
38
+ if parent:
39
+ raise ValueError(f'{path!r} must be only a file name')
40
+ return file_name
41
+
42
+
43
+ @deprecated
44
+ def open_binary(package: Package, resource: Resource) -> BinaryIO:
45
+ """Return a file-like object opened for binary reading of the resource."""
46
+ return (_common.files(package) / normalize_path(resource)).open('rb')
47
+
48
+
49
+ @deprecated
50
+ def read_binary(package: Package, resource: Resource) -> bytes:
51
+ """Return the binary contents of the resource."""
52
+ return (_common.files(package) / normalize_path(resource)).read_bytes()
53
+
54
+
55
+ @deprecated
56
+ def open_text(
57
+ package: Package,
58
+ resource: Resource,
59
+ encoding: str = 'utf-8',
60
+ errors: str = 'strict',
61
+ ) -> TextIO:
62
+ """Return a file-like object opened for text reading of the resource."""
63
+ return (_common.files(package) / normalize_path(resource)).open(
64
+ 'r', encoding=encoding, errors=errors
65
+ )
66
+
67
+
68
+ @deprecated
69
+ def read_text(
70
+ package: Package,
71
+ resource: Resource,
72
+ encoding: str = 'utf-8',
73
+ errors: str = 'strict',
74
+ ) -> str:
75
+ """Return the decoded string of the resource.
76
+
77
+ The decoding-related arguments have the same semantics as those of
78
+ bytes.decode().
79
+ """
80
+ with open_text(package, resource, encoding, errors) as fp:
81
+ return fp.read()
82
+
83
+
84
+ @deprecated
85
+ def contents(package: Package) -> Iterable[str]:
86
+ """Return an iterable of entries in `package`.
87
+
88
+ Note that not all entries are resources. Specifically, directories are
89
+ not considered resources. Use `is_resource()` on each entry returned here
90
+ to check if it is a resource or not.
91
+ """
92
+ return [path.name for path in _common.files(package).iterdir()]
93
+
94
+
95
+ @deprecated
96
+ def is_resource(package: Package, name: str) -> bool:
97
+ """True if `name` is a resource inside `package`.
98
+
99
+ Directories are *not* resources.
100
+ """
101
+ resource = normalize_path(name)
102
+ return any(
103
+ traversable.name == resource and traversable.is_file()
104
+ for traversable in _common.files(package).iterdir()
105
+ )
106
+
107
+
108
+ @deprecated
109
+ def path(
110
+ package: Package,
111
+ resource: Resource,
112
+ ) -> ContextManager[pathlib.Path]:
113
+ """A context manager providing a file path object to the resource.
114
+
115
+ If the resource does not already exist on its own on the file system,
116
+ a temporary file will be created. If the file was created, the file
117
+ will be deleted upon exiting the context manager (no exception is
118
+ raised if the file was deleted prior to the context manager
119
+ exiting).
120
+ """
121
+ return _common.as_file(_common.files(package) / normalize_path(resource))
physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/abc.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import io
3
+ import os
4
+ from typing import Any, BinaryIO, Iterable, Iterator, NoReturn, Text, Optional
5
+ from typing import runtime_checkable, Protocol
6
+ from typing import Union
7
+
8
+
9
+ StrPath = Union[str, os.PathLike[str]]
10
+
11
+ __all__ = ["ResourceReader", "Traversable", "TraversableResources"]
12
+
13
+
14
+ class ResourceReader(metaclass=abc.ABCMeta):
15
+ """Abstract base class for loaders to provide resource reading support."""
16
+
17
+ @abc.abstractmethod
18
+ def open_resource(self, resource: Text) -> BinaryIO:
19
+ """Return an opened, file-like object for binary reading.
20
+
21
+ The 'resource' argument is expected to represent only a file name.
22
+ If the resource cannot be found, FileNotFoundError is raised.
23
+ """
24
+ # This deliberately raises FileNotFoundError instead of
25
+ # NotImplementedError so that if this method is accidentally called,
26
+ # it'll still do the right thing.
27
+ raise FileNotFoundError
28
+
29
+ @abc.abstractmethod
30
+ def resource_path(self, resource: Text) -> Text:
31
+ """Return the file system path to the specified resource.
32
+
33
+ The 'resource' argument is expected to represent only a file name.
34
+ If the resource does not exist on the file system, raise
35
+ FileNotFoundError.
36
+ """
37
+ # This deliberately raises FileNotFoundError instead of
38
+ # NotImplementedError so that if this method is accidentally called,
39
+ # it'll still do the right thing.
40
+ raise FileNotFoundError
41
+
42
+ @abc.abstractmethod
43
+ def is_resource(self, path: Text) -> bool:
44
+ """Return True if the named 'path' is a resource.
45
+
46
+ Files are resources, directories are not.
47
+ """
48
+ raise FileNotFoundError
49
+
50
+ @abc.abstractmethod
51
+ def contents(self) -> Iterable[str]:
52
+ """Return an iterable of entries in `package`."""
53
+ raise FileNotFoundError
54
+
55
+
56
+ @runtime_checkable
57
+ class Traversable(Protocol):
58
+ """
59
+ An object with a subset of pathlib.Path methods suitable for
60
+ traversing directories and opening files.
61
+
62
+ Any exceptions that occur when accessing the backing resource
63
+ may propagate unaltered.
64
+ """
65
+
66
+ @abc.abstractmethod
67
+ def iterdir(self) -> Iterator["Traversable"]:
68
+ """
69
+ Yield Traversable objects in self
70
+ """
71
+
72
+ def read_bytes(self) -> bytes:
73
+ """
74
+ Read contents of self as bytes
75
+ """
76
+ with self.open('rb') as strm:
77
+ return strm.read()
78
+
79
+ def read_text(self, encoding: Optional[str] = None) -> str:
80
+ """
81
+ Read contents of self as text
82
+ """
83
+ with self.open(encoding=encoding) as strm:
84
+ return strm.read()
85
+
86
+ @abc.abstractmethod
87
+ def is_dir(self) -> bool:
88
+ """
89
+ Return True if self is a directory
90
+ """
91
+
92
+ @abc.abstractmethod
93
+ def is_file(self) -> bool:
94
+ """
95
+ Return True if self is a file
96
+ """
97
+
98
+ @abc.abstractmethod
99
+ def joinpath(self, *descendants: StrPath) -> "Traversable":
100
+ """
101
+ Return Traversable resolved with any descendants applied.
102
+
103
+ Each descendant should be a path segment relative to self
104
+ and each may contain multiple levels separated by
105
+ ``posixpath.sep`` (``/``).
106
+ """
107
+
108
+ def __truediv__(self, child: StrPath) -> "Traversable":
109
+ """
110
+ Return Traversable child in self
111
+ """
112
+ return self.joinpath(child)
113
+
114
+ @abc.abstractmethod
115
+ def open(self, mode='r', *args, **kwargs):
116
+ """
117
+ mode may be 'r' or 'rb' to open as text or binary. Return a handle
118
+ suitable for reading (same as pathlib.Path.open).
119
+
120
+ When opening as text, accepts encoding parameters such as those
121
+ accepted by io.TextIOWrapper.
122
+ """
123
+
124
+ @abc.abstractproperty
125
+ def name(self) -> str:
126
+ """
127
+ The base name of this object without any parent references.
128
+ """
129
+
130
+
131
+ class TraversableResources(ResourceReader):
132
+ """
133
+ The required interface for providing traversable
134
+ resources.
135
+ """
136
+
137
+ @abc.abstractmethod
138
+ def files(self) -> "Traversable":
139
+ """Return a Traversable object for the loaded package."""
140
+
141
+ def open_resource(self, resource: StrPath) -> io.BufferedReader:
142
+ return self.files().joinpath(resource).open('rb')
143
+
144
+ def resource_path(self, resource: Any) -> NoReturn:
145
+ raise FileNotFoundError(resource)
146
+
147
+ def is_resource(self, path: StrPath) -> bool:
148
+ return self.files().joinpath(path).is_file()
149
+
150
+ def contents(self) -> Iterator[str]:
151
+ return (item.name for item in self.files().iterdir())
physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/readers.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import operator
3
+ import pathlib
4
+ import zipfile
5
+
6
+ from . import abc
7
+
8
+ from ._itertools import unique_everseen
9
+
10
+
11
+ def remove_duplicates(items):
12
+ return iter(collections.OrderedDict.fromkeys(items))
13
+
14
+
15
+ class FileReader(abc.TraversableResources):
16
+ def __init__(self, loader):
17
+ self.path = pathlib.Path(loader.path).parent
18
+
19
+ def resource_path(self, resource):
20
+ """
21
+ Return the file system path to prevent
22
+ `resources.path()` from creating a temporary
23
+ copy.
24
+ """
25
+ return str(self.path.joinpath(resource))
26
+
27
+ def files(self):
28
+ return self.path
29
+
30
+
31
+ class ZipReader(abc.TraversableResources):
32
+ def __init__(self, loader, module):
33
+ _, _, name = module.rpartition('.')
34
+ self.prefix = loader.prefix.replace('\\', '/') + name + '/'
35
+ self.archive = loader.archive
36
+
37
+ def open_resource(self, resource):
38
+ try:
39
+ return super().open_resource(resource)
40
+ except KeyError as exc:
41
+ raise FileNotFoundError(exc.args[0])
42
+
43
+ def is_resource(self, path):
44
+ # workaround for `zipfile.Path.is_file` returning true
45
+ # for non-existent paths.
46
+ target = self.files().joinpath(path)
47
+ return target.is_file() and target.exists()
48
+
49
+ def files(self):
50
+ return zipfile.Path(self.archive, self.prefix)
51
+
52
+
53
+ class MultiplexedPath(abc.Traversable):
54
+ """
55
+ Given a series of Traversable objects, implement a merged
56
+ version of the interface across all objects. Useful for
57
+ namespace packages which may be multihomed at a single
58
+ name.
59
+ """
60
+
61
+ def __init__(self, *paths):
62
+ self._paths = list(map(pathlib.Path, remove_duplicates(paths)))
63
+ if not self._paths:
64
+ message = 'MultiplexedPath must contain at least one path'
65
+ raise FileNotFoundError(message)
66
+ if not all(path.is_dir() for path in self._paths):
67
+ raise NotADirectoryError('MultiplexedPath only supports directories')
68
+
69
+ def iterdir(self):
70
+ files = (file for path in self._paths for file in path.iterdir())
71
+ return unique_everseen(files, key=operator.attrgetter('name'))
72
+
73
+ def read_bytes(self):
74
+ raise FileNotFoundError(f'{self} is not a file')
75
+
76
+ def read_text(self, *args, **kwargs):
77
+ raise FileNotFoundError(f'{self} is not a file')
78
+
79
+ def is_dir(self):
80
+ return True
81
+
82
+ def is_file(self):
83
+ return False
84
+
85
+ def joinpath(self, child):
86
+ # first try to find child in current paths
87
+ for file in self.iterdir():
88
+ if file.name == child:
89
+ return file
90
+ # if it does not exist, construct it with the first path
91
+ return self._paths[0] / child
92
+
93
+ __truediv__ = joinpath
94
+
95
+ def open(self, *args, **kwargs):
96
+ raise FileNotFoundError(f'{self} is not a file')
97
+
98
+ @property
99
+ def name(self):
100
+ return self._paths[0].name
101
+
102
+ def __repr__(self):
103
+ paths = ', '.join(f"'{path}'" for path in self._paths)
104
+ return f'MultiplexedPath({paths})'
105
+
106
+
107
+ class NamespaceReader(abc.TraversableResources):
108
+ def __init__(self, namespace_path):
109
+ if 'NamespacePath' not in str(namespace_path):
110
+ raise ValueError('Invalid path')
111
+ self.path = MultiplexedPath(*list(namespace_path))
112
+
113
+ def resource_path(self, resource):
114
+ """
115
+ Return the file system path to prevent
116
+ `resources.path()` from creating a temporary
117
+ copy.
118
+ """
119
+ return str(self.path.joinpath(resource))
120
+
121
+ def files(self):
122
+ return self.path
physworld_p1_20261018/envs/p1/lib/python3.11/importlib/resources/simple.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Interface adapters for low-level readers.
3
+ """
4
+
5
+ import abc
6
+ import io
7
+ import itertools
8
+ from typing import BinaryIO, List
9
+
10
+ from .abc import Traversable, TraversableResources
11
+
12
+
13
+ class SimpleReader(abc.ABC):
14
+ """
15
+ The minimum, low-level interface required from a resource
16
+ provider.
17
+ """
18
+
19
+ @abc.abstractproperty
20
+ def package(self):
21
+ # type: () -> str
22
+ """
23
+ The name of the package for which this reader loads resources.
24
+ """
25
+
26
+ @abc.abstractmethod
27
+ def children(self):
28
+ # type: () -> List['SimpleReader']
29
+ """
30
+ Obtain an iterable of SimpleReader for available
31
+ child containers (e.g. directories).
32
+ """
33
+
34
+ @abc.abstractmethod
35
+ def resources(self):
36
+ # type: () -> List[str]
37
+ """
38
+ Obtain available named resources for this virtual package.
39
+ """
40
+
41
+ @abc.abstractmethod
42
+ def open_binary(self, resource):
43
+ # type: (str) -> BinaryIO
44
+ """
45
+ Obtain a File-like for a named resource.
46
+ """
47
+
48
+ @property
49
+ def name(self):
50
+ return self.package.split('.')[-1]
51
+
52
+
53
+ class ResourceHandle(Traversable):
54
+ """
55
+ Handle to a named resource in a ResourceReader.
56
+ """
57
+
58
+ def __init__(self, parent, name):
59
+ # type: (ResourceContainer, str) -> None
60
+ self.parent = parent
61
+ self.name = name # type: ignore
62
+
63
+ def is_file(self):
64
+ return True
65
+
66
+ def is_dir(self):
67
+ return False
68
+
69
+ def open(self, mode='r', *args, **kwargs):
70
+ stream = self.parent.reader.open_binary(self.name)
71
+ if 'b' not in mode:
72
+ stream = io.TextIOWrapper(stream, *args, **kwargs)
73
+ return stream
74
+
75
+ def joinpath(self, name):
76
+ raise RuntimeError("Cannot traverse into a resource")
77
+
78
+
79
+ class ResourceContainer(Traversable):
80
+ """
81
+ Traversable container for a package's resources via its reader.
82
+ """
83
+
84
+ def __init__(self, reader):
85
+ # type: (SimpleReader) -> None
86
+ self.reader = reader
87
+
88
+ def is_dir(self):
89
+ return True
90
+
91
+ def is_file(self):
92
+ return False
93
+
94
+ def iterdir(self):
95
+ files = (ResourceHandle(self, name) for name in self.reader.resources)
96
+ dirs = map(ResourceContainer, self.reader.children())
97
+ return itertools.chain(files, dirs)
98
+
99
+ def open(self, *args, **kwargs):
100
+ raise IsADirectoryError()
101
+
102
+ @staticmethod
103
+ def _flatten(compound_names):
104
+ for name in compound_names:
105
+ yield from name.split('/')
106
+
107
+ def joinpath(self, *descendants):
108
+ if not descendants:
109
+ return self
110
+ names = self._flatten(descendants)
111
+ target = next(names)
112
+ return next(
113
+ traversable for traversable in self.iterdir() if traversable.name == target
114
+ ).joinpath(*names)
115
+
116
+
117
+ class TraversableReader(TraversableResources, SimpleReader):
118
+ """
119
+ A TraversableResources based on SimpleReader. Resource providers
120
+ may derive from this class to provide the TraversableResources
121
+ interface by supplying the SimpleReader interface.
122
+ """
123
+
124
+ def files(self):
125
+ return ResourceContainer(self)
physworld_p1_20261018/envs/p1/lib/python3.11/importlib/simple.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Compatibility shim for .resources.simple as found on Python 3.10.
3
+
4
+ Consumers that can rely on Python 3.11 should use the other
5
+ module directly.
6
+ """
7
+
8
+ from .resources.simple import (
9
+ SimpleReader, ResourceHandle, ResourceContainer, TraversableReader,
10
+ )
11
+
12
+ __all__ = [
13
+ 'SimpleReader', 'ResourceHandle', 'ResourceContainer', 'TraversableReader',
14
+ ]
physworld_p1_20261018/envs/p1/lib/python3.11/importlib/util.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utility code for constructing importers, etc."""
2
+ from ._abc import Loader
3
+ from ._bootstrap import module_from_spec
4
+ from ._bootstrap import _resolve_name
5
+ from ._bootstrap import spec_from_loader
6
+ from ._bootstrap import _find_spec
7
+ from ._bootstrap_external import MAGIC_NUMBER
8
+ from ._bootstrap_external import _RAW_MAGIC_NUMBER
9
+ from ._bootstrap_external import cache_from_source
10
+ from ._bootstrap_external import decode_source
11
+ from ._bootstrap_external import source_from_cache
12
+ from ._bootstrap_external import spec_from_file_location
13
+
14
+ from contextlib import contextmanager
15
+ import _imp
16
+ import functools
17
+ import sys
18
+ import threading
19
+ import types
20
+ import warnings
21
+
22
+
23
+ def source_hash(source_bytes):
24
+ "Return the hash of *source_bytes* as used in hash-based pyc files."
25
+ return _imp.source_hash(_RAW_MAGIC_NUMBER, source_bytes)
26
+
27
+
28
+ def resolve_name(name, package):
29
+ """Resolve a relative module name to an absolute one."""
30
+ if not name.startswith('.'):
31
+ return name
32
+ elif not package:
33
+ raise ImportError(f'no package specified for {repr(name)} '
34
+ '(required for relative module names)')
35
+ level = 0
36
+ for character in name:
37
+ if character != '.':
38
+ break
39
+ level += 1
40
+ return _resolve_name(name[level:], package, level)
41
+
42
+
43
+ def _find_spec_from_path(name, path=None):
44
+ """Return the spec for the specified module.
45
+
46
+ First, sys.modules is checked to see if the module was already imported. If
47
+ so, then sys.modules[name].__spec__ is returned. If that happens to be
48
+ set to None, then ValueError is raised. If the module is not in
49
+ sys.modules, then sys.meta_path is searched for a suitable spec with the
50
+ value of 'path' given to the finders. None is returned if no spec could
51
+ be found.
52
+
53
+ Dotted names do not have their parent packages implicitly imported. You will
54
+ most likely need to explicitly import all parent packages in the proper
55
+ order for a submodule to get the correct spec.
56
+
57
+ """
58
+ if name not in sys.modules:
59
+ return _find_spec(name, path)
60
+ else:
61
+ module = sys.modules[name]
62
+ if module is None:
63
+ return None
64
+ try:
65
+ spec = module.__spec__
66
+ except AttributeError:
67
+ raise ValueError('{}.__spec__ is not set'.format(name)) from None
68
+ else:
69
+ if spec is None:
70
+ raise ValueError('{}.__spec__ is None'.format(name))
71
+ return spec
72
+
73
+
74
+ def find_spec(name, package=None):
75
+ """Return the spec for the specified module.
76
+
77
+ First, sys.modules is checked to see if the module was already imported. If
78
+ so, then sys.modules[name].__spec__ is returned. If that happens to be
79
+ set to None, then ValueError is raised. If the module is not in
80
+ sys.modules, then sys.meta_path is searched for a suitable spec with the
81
+ value of 'path' given to the finders. None is returned if no spec could
82
+ be found.
83
+
84
+ If the name is for submodule (contains a dot), the parent module is
85
+ automatically imported.
86
+
87
+ The name and package arguments work the same as importlib.import_module().
88
+ In other words, relative module names (with leading dots) work.
89
+
90
+ """
91
+ fullname = resolve_name(name, package) if name.startswith('.') else name
92
+ if fullname not in sys.modules:
93
+ parent_name = fullname.rpartition('.')[0]
94
+ if parent_name:
95
+ parent = __import__(parent_name, fromlist=['__path__'])
96
+ try:
97
+ parent_path = parent.__path__
98
+ except AttributeError as e:
99
+ raise ModuleNotFoundError(
100
+ f"__path__ attribute not found on {parent_name!r} "
101
+ f"while trying to find {fullname!r}", name=fullname) from e
102
+ else:
103
+ parent_path = None
104
+ return _find_spec(fullname, parent_path)
105
+ else:
106
+ module = sys.modules[fullname]
107
+ if module is None:
108
+ return None
109
+ try:
110
+ spec = module.__spec__
111
+ except AttributeError:
112
+ raise ValueError('{}.__spec__ is not set'.format(name)) from None
113
+ else:
114
+ if spec is None:
115
+ raise ValueError('{}.__spec__ is None'.format(name))
116
+ return spec
117
+
118
+
119
+ @contextmanager
120
+ def _module_to_load(name):
121
+ is_reload = name in sys.modules
122
+
123
+ module = sys.modules.get(name)
124
+ if not is_reload:
125
+ # This must be done before open() is called as the 'io' module
126
+ # implicitly imports 'locale' and would otherwise trigger an
127
+ # infinite loop.
128
+ module = type(sys)(name)
129
+ # This must be done before putting the module in sys.modules
130
+ # (otherwise an optimization shortcut in import.c becomes wrong)
131
+ module.__initializing__ = True
132
+ sys.modules[name] = module
133
+ try:
134
+ yield module
135
+ except Exception:
136
+ if not is_reload:
137
+ try:
138
+ del sys.modules[name]
139
+ except KeyError:
140
+ pass
141
+ finally:
142
+ module.__initializing__ = False
143
+
144
+
145
+ def set_package(fxn):
146
+ """Set __package__ on the returned module.
147
+
148
+ This function is deprecated.
149
+
150
+ """
151
+ @functools.wraps(fxn)
152
+ def set_package_wrapper(*args, **kwargs):
153
+ warnings.warn('The import system now takes care of this automatically; '
154
+ 'this decorator is slated for removal in Python 3.12',
155
+ DeprecationWarning, stacklevel=2)
156
+ module = fxn(*args, **kwargs)
157
+ if getattr(module, '__package__', None) is None:
158
+ module.__package__ = module.__name__
159
+ if not hasattr(module, '__path__'):
160
+ module.__package__ = module.__package__.rpartition('.')[0]
161
+ return module
162
+ return set_package_wrapper
163
+
164
+
165
+ def set_loader(fxn):
166
+ """Set __loader__ on the returned module.
167
+
168
+ This function is deprecated.
169
+
170
+ """
171
+ @functools.wraps(fxn)
172
+ def set_loader_wrapper(self, *args, **kwargs):
173
+ warnings.warn('The import system now takes care of this automatically; '
174
+ 'this decorator is slated for removal in Python 3.12',
175
+ DeprecationWarning, stacklevel=2)
176
+ module = fxn(self, *args, **kwargs)
177
+ if getattr(module, '__loader__', None) is None:
178
+ module.__loader__ = self
179
+ return module
180
+ return set_loader_wrapper
181
+
182
+
183
+ def module_for_loader(fxn):
184
+ """Decorator to handle selecting the proper module for loaders.
185
+
186
+ The decorated function is passed the module to use instead of the module
187
+ name. The module passed in to the function is either from sys.modules if
188
+ it already exists or is a new module. If the module is new, then __name__
189
+ is set the first argument to the method, __loader__ is set to self, and
190
+ __package__ is set accordingly (if self.is_package() is defined) will be set
191
+ before it is passed to the decorated function (if self.is_package() does
192
+ not work for the module it will be set post-load).
193
+
194
+ If an exception is raised and the decorator created the module it is
195
+ subsequently removed from sys.modules.
196
+
197
+ The decorator assumes that the decorated function takes the module name as
198
+ the second argument.
199
+
200
+ """
201
+ warnings.warn('The import system now takes care of this automatically; '
202
+ 'this decorator is slated for removal in Python 3.12',
203
+ DeprecationWarning, stacklevel=2)
204
+ @functools.wraps(fxn)
205
+ def module_for_loader_wrapper(self, fullname, *args, **kwargs):
206
+ with _module_to_load(fullname) as module:
207
+ module.__loader__ = self
208
+ try:
209
+ is_package = self.is_package(fullname)
210
+ except (ImportError, AttributeError):
211
+ pass
212
+ else:
213
+ if is_package:
214
+ module.__package__ = fullname
215
+ else:
216
+ module.__package__ = fullname.rpartition('.')[0]
217
+ # If __package__ was not set above, __import__() will do it later.
218
+ return fxn(self, module, *args, **kwargs)
219
+
220
+ return module_for_loader_wrapper
221
+
222
+
223
+ class _LazyModule(types.ModuleType):
224
+
225
+ """A subclass of the module type which triggers loading upon attribute access."""
226
+
227
+ def __getattribute__(self, attr):
228
+ """Trigger the load of the module and return the attribute."""
229
+ __spec__ = object.__getattribute__(self, '__spec__')
230
+ loader_state = __spec__.loader_state
231
+ with loader_state['lock']:
232
+ # Only the first thread to get the lock should trigger the load
233
+ # and reset the module's class. The rest can now getattr().
234
+ if object.__getattribute__(self, '__class__') is _LazyModule:
235
+ # Reentrant calls from the same thread must be allowed to proceed without
236
+ # triggering the load again.
237
+ # exec_module() and self-referential imports are the primary ways this can
238
+ # happen, but in any case we must return something to avoid deadlock.
239
+ if loader_state['is_loading']:
240
+ return object.__getattribute__(self, attr)
241
+ loader_state['is_loading'] = True
242
+
243
+ __dict__ = object.__getattribute__(self, '__dict__')
244
+
245
+ # All module metadata must be gathered from __spec__ in order to avoid
246
+ # using mutated values.
247
+ # Get the original name to make sure no object substitution occurred
248
+ # in sys.modules.
249
+ original_name = __spec__.name
250
+ # Figure out exactly what attributes were mutated between the creation
251
+ # of the module and now.
252
+ attrs_then = loader_state['__dict__']
253
+ attrs_now = __dict__
254
+ attrs_updated = {}
255
+ for key, value in attrs_now.items():
256
+ # Code that set an attribute may have kept a reference to the
257
+ # assigned object, making identity more important than equality.
258
+ if key not in attrs_then:
259
+ attrs_updated[key] = value
260
+ elif id(attrs_now[key]) != id(attrs_then[key]):
261
+ attrs_updated[key] = value
262
+ __spec__.loader.exec_module(self)
263
+ # If exec_module() was used directly there is no guarantee the module
264
+ # object was put into sys.modules.
265
+ if original_name in sys.modules:
266
+ if id(self) != id(sys.modules[original_name]):
267
+ raise ValueError(f"module object for {original_name!r} "
268
+ "substituted in sys.modules during a lazy "
269
+ "load")
270
+ # Update after loading since that's what would happen in an eager
271
+ # loading situation.
272
+ __dict__.update(attrs_updated)
273
+ # Finally, stop triggering this method.
274
+ self.__class__ = types.ModuleType
275
+
276
+ return getattr(self, attr)
277
+
278
+ def __delattr__(self, attr):
279
+ """Trigger the load and then perform the deletion."""
280
+ # To trigger the load and raise an exception if the attribute
281
+ # doesn't exist.
282
+ self.__getattribute__(attr)
283
+ delattr(self, attr)
284
+
285
+
286
+ class LazyLoader(Loader):
287
+
288
+ """A loader that creates a module which defers loading until attribute access."""
289
+
290
+ @staticmethod
291
+ def __check_eager_loader(loader):
292
+ if not hasattr(loader, 'exec_module'):
293
+ raise TypeError('loader must define exec_module()')
294
+
295
+ @classmethod
296
+ def factory(cls, loader):
297
+ """Construct a callable which returns the eager loader made lazy."""
298
+ cls.__check_eager_loader(loader)
299
+ return lambda *args, **kwargs: cls(loader(*args, **kwargs))
300
+
301
+ def __init__(self, loader):
302
+ self.__check_eager_loader(loader)
303
+ self.loader = loader
304
+
305
+ def create_module(self, spec):
306
+ return self.loader.create_module(spec)
307
+
308
+ def exec_module(self, module):
309
+ """Make the module load lazily."""
310
+ module.__spec__.loader = self.loader
311
+ module.__loader__ = self.loader
312
+ # Don't need to worry about deep-copying as trying to set an attribute
313
+ # on an object would have triggered the load,
314
+ # e.g. ``module.__spec__.loader = None`` would trigger a load from
315
+ # trying to access module.__spec__.
316
+ loader_state = {}
317
+ loader_state['__dict__'] = module.__dict__.copy()
318
+ loader_state['__class__'] = module.__class__
319
+ loader_state['lock'] = threading.RLock()
320
+ loader_state['is_loading'] = False
321
+ module.__spec__.loader_state = loader_state
322
+ module.__class__ = _LazyModule
physworld_p1_20261018/envs/p1/lib/python3.11/inspect.py ADDED
The diff for this file is too large to render. See raw diff
 
physworld_p1_20261018/envs/p1/lib/python3.11/io.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The io module provides the Python interfaces to stream handling. The
2
+ builtin open function is defined in this module.
3
+
4
+ At the top of the I/O hierarchy is the abstract base class IOBase. It
5
+ defines the basic interface to a stream. Note, however, that there is no
6
+ separation between reading and writing to streams; implementations are
7
+ allowed to raise an OSError if they do not support a given operation.
8
+
9
+ Extending IOBase is RawIOBase which deals simply with the reading and
10
+ writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide
11
+ an interface to OS files.
12
+
13
+ BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its
14
+ subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer
15
+ streams that are readable, writable, and both respectively.
16
+ BufferedRandom provides a buffered interface to random access
17
+ streams. BytesIO is a simple stream of in-memory bytes.
18
+
19
+ Another IOBase subclass, TextIOBase, deals with the encoding and decoding
20
+ of streams into text. TextIOWrapper, which extends it, is a buffered text
21
+ interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO
22
+ is an in-memory stream for text.
23
+
24
+ Argument names are not part of the specification, and only the arguments
25
+ of open() are intended to be used as keyword arguments.
26
+
27
+ data:
28
+
29
+ DEFAULT_BUFFER_SIZE
30
+
31
+ An int containing the default buffer size used by the module's buffered
32
+ I/O classes. open() uses the file's blksize (as obtained by os.stat) if
33
+ possible.
34
+ """
35
+ # New I/O library conforming to PEP 3116.
36
+
37
+ __author__ = ("Guido van Rossum <guido@python.org>, "
38
+ "Mike Verdone <mike.verdone@gmail.com>, "
39
+ "Mark Russell <mark.russell@zen.co.uk>, "
40
+ "Antoine Pitrou <solipsis@pitrou.net>, "
41
+ "Amaury Forgeot d'Arc <amauryfa@gmail.com>, "
42
+ "Benjamin Peterson <benjamin@python.org>")
43
+
44
+ __all__ = ["BlockingIOError", "open", "open_code", "IOBase", "RawIOBase",
45
+ "FileIO", "BytesIO", "StringIO", "BufferedIOBase",
46
+ "BufferedReader", "BufferedWriter", "BufferedRWPair",
47
+ "BufferedRandom", "TextIOBase", "TextIOWrapper",
48
+ "UnsupportedOperation", "SEEK_SET", "SEEK_CUR", "SEEK_END",
49
+ "DEFAULT_BUFFER_SIZE", "text_encoding", "IncrementalNewlineDecoder"]
50
+
51
+
52
+ import _io
53
+ import abc
54
+
55
+ from _io import (DEFAULT_BUFFER_SIZE, BlockingIOError, UnsupportedOperation,
56
+ open, open_code, FileIO, BytesIO, StringIO, BufferedReader,
57
+ BufferedWriter, BufferedRWPair, BufferedRandom,
58
+ IncrementalNewlineDecoder, text_encoding, TextIOWrapper)
59
+
60
+
61
+ def __getattr__(name):
62
+ if name == "OpenWrapper":
63
+ # bpo-43680: Until Python 3.9, _pyio.open was not a static method and
64
+ # builtins.open was set to OpenWrapper to not become a bound method
65
+ # when set to a class variable. _io.open is a built-in function whereas
66
+ # _pyio.open is a Python function. In Python 3.10, _pyio.open() is now
67
+ # a static method, and builtins.open() is now io.open().
68
+ import warnings
69
+ warnings.warn('OpenWrapper is deprecated, use open instead',
70
+ DeprecationWarning, stacklevel=2)
71
+ global OpenWrapper
72
+ OpenWrapper = open
73
+ return OpenWrapper
74
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
75
+
76
+
77
+ # Pretend this exception was created here.
78
+ UnsupportedOperation.__module__ = "io"
79
+
80
+ # for seek()
81
+ SEEK_SET = 0
82
+ SEEK_CUR = 1
83
+ SEEK_END = 2
84
+
85
+ # Declaring ABCs in C is tricky so we do it here.
86
+ # Method descriptions and default implementations are inherited from the C
87
+ # version however.
88
+ class IOBase(_io._IOBase, metaclass=abc.ABCMeta):
89
+ __doc__ = _io._IOBase.__doc__
90
+
91
+ class RawIOBase(_io._RawIOBase, IOBase):
92
+ __doc__ = _io._RawIOBase.__doc__
93
+
94
+ class BufferedIOBase(_io._BufferedIOBase, IOBase):
95
+ __doc__ = _io._BufferedIOBase.__doc__
96
+
97
+ class TextIOBase(_io._TextIOBase, IOBase):
98
+ __doc__ = _io._TextIOBase.__doc__
99
+
100
+ RawIOBase.register(FileIO)
101
+
102
+ for klass in (BytesIO, BufferedReader, BufferedWriter, BufferedRandom,
103
+ BufferedRWPair):
104
+ BufferedIOBase.register(klass)
105
+
106
+ for klass in (StringIO, TextIOWrapper):
107
+ TextIOBase.register(klass)
108
+ del klass
109
+
110
+ try:
111
+ from _io import _WindowsConsoleIO
112
+ except ImportError:
113
+ pass
114
+ else:
115
+ RawIOBase.register(_WindowsConsoleIO)
physworld_p1_20261018/envs/p1/lib/python3.11/ipaddress.py ADDED
@@ -0,0 +1,2430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2007 Google Inc.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """A fast, lightweight IPv4/IPv6 manipulation library in Python.
5
+
6
+ This library is used to create/poke/manipulate IPv4 and IPv6 addresses
7
+ and networks.
8
+
9
+ """
10
+
11
+ __version__ = '1.0'
12
+
13
+
14
+ import functools
15
+
16
+ IPV4LENGTH = 32
17
+ IPV6LENGTH = 128
18
+
19
+
20
+ class AddressValueError(ValueError):
21
+ """A Value Error related to the address."""
22
+
23
+
24
+ class NetmaskValueError(ValueError):
25
+ """A Value Error related to the netmask."""
26
+
27
+
28
+ def ip_address(address):
29
+ """Take an IP string/int and return an object of the correct type.
30
+
31
+ Args:
32
+ address: A string or integer, the IP address. Either IPv4 or
33
+ IPv6 addresses may be supplied; integers less than 2**32 will
34
+ be considered to be IPv4 by default.
35
+
36
+ Returns:
37
+ An IPv4Address or IPv6Address object.
38
+
39
+ Raises:
40
+ ValueError: if the *address* passed isn't either a v4 or a v6
41
+ address
42
+
43
+ """
44
+ try:
45
+ return IPv4Address(address)
46
+ except (AddressValueError, NetmaskValueError):
47
+ pass
48
+
49
+ try:
50
+ return IPv6Address(address)
51
+ except (AddressValueError, NetmaskValueError):
52
+ pass
53
+
54
+ raise ValueError(f'{address!r} does not appear to be an IPv4 or IPv6 address')
55
+
56
+
57
+ def ip_network(address, strict=True):
58
+ """Take an IP string/int and return an object of the correct type.
59
+
60
+ Args:
61
+ address: A string or integer, the IP network. Either IPv4 or
62
+ IPv6 networks may be supplied; integers less than 2**32 will
63
+ be considered to be IPv4 by default.
64
+
65
+ Returns:
66
+ An IPv4Network or IPv6Network object.
67
+
68
+ Raises:
69
+ ValueError: if the string passed isn't either a v4 or a v6
70
+ address. Or if the network has host bits set.
71
+
72
+ """
73
+ try:
74
+ return IPv4Network(address, strict)
75
+ except (AddressValueError, NetmaskValueError):
76
+ pass
77
+
78
+ try:
79
+ return IPv6Network(address, strict)
80
+ except (AddressValueError, NetmaskValueError):
81
+ pass
82
+
83
+ raise ValueError(f'{address!r} does not appear to be an IPv4 or IPv6 network')
84
+
85
+
86
+ def ip_interface(address):
87
+ """Take an IP string/int and return an object of the correct type.
88
+
89
+ Args:
90
+ address: A string or integer, the IP address. Either IPv4 or
91
+ IPv6 addresses may be supplied; integers less than 2**32 will
92
+ be considered to be IPv4 by default.
93
+
94
+ Returns:
95
+ An IPv4Interface or IPv6Interface object.
96
+
97
+ Raises:
98
+ ValueError: if the string passed isn't either a v4 or a v6
99
+ address.
100
+
101
+ Notes:
102
+ The IPv?Interface classes describe an Address on a particular
103
+ Network, so they're basically a combination of both the Address
104
+ and Network classes.
105
+
106
+ """
107
+ try:
108
+ return IPv4Interface(address)
109
+ except (AddressValueError, NetmaskValueError):
110
+ pass
111
+
112
+ try:
113
+ return IPv6Interface(address)
114
+ except (AddressValueError, NetmaskValueError):
115
+ pass
116
+
117
+ raise ValueError(f'{address!r} does not appear to be an IPv4 or IPv6 interface')
118
+
119
+
120
+ def v4_int_to_packed(address):
121
+ """Represent an address as 4 packed bytes in network (big-endian) order.
122
+
123
+ Args:
124
+ address: An integer representation of an IPv4 IP address.
125
+
126
+ Returns:
127
+ The integer address packed as 4 bytes in network (big-endian) order.
128
+
129
+ Raises:
130
+ ValueError: If the integer is negative or too large to be an
131
+ IPv4 IP address.
132
+
133
+ """
134
+ try:
135
+ return address.to_bytes(4) # big endian
136
+ except OverflowError:
137
+ raise ValueError("Address negative or too large for IPv4")
138
+
139
+
140
+ def v6_int_to_packed(address):
141
+ """Represent an address as 16 packed bytes in network (big-endian) order.
142
+
143
+ Args:
144
+ address: An integer representation of an IPv6 IP address.
145
+
146
+ Returns:
147
+ The integer address packed as 16 bytes in network (big-endian) order.
148
+
149
+ """
150
+ try:
151
+ return address.to_bytes(16) # big endian
152
+ except OverflowError:
153
+ raise ValueError("Address negative or too large for IPv6")
154
+
155
+
156
+ def _split_optional_netmask(address):
157
+ """Helper to split the netmask and raise AddressValueError if needed"""
158
+ addr = str(address).split('/')
159
+ if len(addr) > 2:
160
+ raise AddressValueError(f"Only one '/' permitted in {address!r}")
161
+ return addr
162
+
163
+
164
+ def _find_address_range(addresses):
165
+ """Find a sequence of sorted deduplicated IPv#Address.
166
+
167
+ Args:
168
+ addresses: a list of IPv#Address objects.
169
+
170
+ Yields:
171
+ A tuple containing the first and last IP addresses in the sequence.
172
+
173
+ """
174
+ it = iter(addresses)
175
+ first = last = next(it)
176
+ for ip in it:
177
+ if ip._ip != last._ip + 1:
178
+ yield first, last
179
+ first = ip
180
+ last = ip
181
+ yield first, last
182
+
183
+
184
+ def _count_righthand_zero_bits(number, bits):
185
+ """Count the number of zero bits on the right hand side.
186
+
187
+ Args:
188
+ number: an integer.
189
+ bits: maximum number of bits to count.
190
+
191
+ Returns:
192
+ The number of zero bits on the right hand side of the number.
193
+
194
+ """
195
+ if number == 0:
196
+ return bits
197
+ return min(bits, (~number & (number-1)).bit_length())
198
+
199
+
200
+ def summarize_address_range(first, last):
201
+ """Summarize a network range given the first and last IP addresses.
202
+
203
+ Example:
204
+ >>> list(summarize_address_range(IPv4Address('192.0.2.0'),
205
+ ... IPv4Address('192.0.2.130')))
206
+ ... #doctest: +NORMALIZE_WHITESPACE
207
+ [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
208
+ IPv4Network('192.0.2.130/32')]
209
+
210
+ Args:
211
+ first: the first IPv4Address or IPv6Address in the range.
212
+ last: the last IPv4Address or IPv6Address in the range.
213
+
214
+ Returns:
215
+ An iterator of the summarized IPv(4|6) network objects.
216
+
217
+ Raise:
218
+ TypeError:
219
+ If the first and last objects are not IP addresses.
220
+ If the first and last objects are not the same version.
221
+ ValueError:
222
+ If the last object is not greater than the first.
223
+ If the version of the first address is not 4 or 6.
224
+
225
+ """
226
+ if (not (isinstance(first, _BaseAddress) and
227
+ isinstance(last, _BaseAddress))):
228
+ raise TypeError('first and last must be IP addresses, not networks')
229
+ if first.version != last.version:
230
+ raise TypeError("%s and %s are not of the same version" % (
231
+ first, last))
232
+ if first > last:
233
+ raise ValueError('last IP address must be greater than first')
234
+
235
+ if first.version == 4:
236
+ ip = IPv4Network
237
+ elif first.version == 6:
238
+ ip = IPv6Network
239
+ else:
240
+ raise ValueError('unknown IP version')
241
+
242
+ ip_bits = first._max_prefixlen
243
+ first_int = first._ip
244
+ last_int = last._ip
245
+ while first_int <= last_int:
246
+ nbits = min(_count_righthand_zero_bits(first_int, ip_bits),
247
+ (last_int - first_int + 1).bit_length() - 1)
248
+ net = ip((first_int, ip_bits - nbits))
249
+ yield net
250
+ first_int += 1 << nbits
251
+ if first_int - 1 == ip._ALL_ONES:
252
+ break
253
+
254
+
255
+ def _collapse_addresses_internal(addresses):
256
+ """Loops through the addresses, collapsing concurrent netblocks.
257
+
258
+ Example:
259
+
260
+ ip1 = IPv4Network('192.0.2.0/26')
261
+ ip2 = IPv4Network('192.0.2.64/26')
262
+ ip3 = IPv4Network('192.0.2.128/26')
263
+ ip4 = IPv4Network('192.0.2.192/26')
264
+
265
+ _collapse_addresses_internal([ip1, ip2, ip3, ip4]) ->
266
+ [IPv4Network('192.0.2.0/24')]
267
+
268
+ This shouldn't be called directly; it is called via
269
+ collapse_addresses([]).
270
+
271
+ Args:
272
+ addresses: A list of IPv4Network's or IPv6Network's
273
+
274
+ Returns:
275
+ A list of IPv4Network's or IPv6Network's depending on what we were
276
+ passed.
277
+
278
+ """
279
+ # First merge
280
+ to_merge = list(addresses)
281
+ subnets = {}
282
+ while to_merge:
283
+ net = to_merge.pop()
284
+ supernet = net.supernet()
285
+ existing = subnets.get(supernet)
286
+ if existing is None:
287
+ subnets[supernet] = net
288
+ elif existing != net:
289
+ # Merge consecutive subnets
290
+ del subnets[supernet]
291
+ to_merge.append(supernet)
292
+ # Then iterate over resulting networks, skipping subsumed subnets
293
+ last = None
294
+ for net in sorted(subnets.values()):
295
+ if last is not None:
296
+ # Since they are sorted, last.network_address <= net.network_address
297
+ # is a given.
298
+ if last.broadcast_address >= net.broadcast_address:
299
+ continue
300
+ yield net
301
+ last = net
302
+
303
+
304
+ def collapse_addresses(addresses):
305
+ """Collapse a list of IP objects.
306
+
307
+ Example:
308
+ collapse_addresses([IPv4Network('192.0.2.0/25'),
309
+ IPv4Network('192.0.2.128/25')]) ->
310
+ [IPv4Network('192.0.2.0/24')]
311
+
312
+ Args:
313
+ addresses: An iterable of IPv4Network or IPv6Network objects.
314
+
315
+ Returns:
316
+ An iterator of the collapsed IPv(4|6)Network objects.
317
+
318
+ Raises:
319
+ TypeError: If passed a list of mixed version objects.
320
+
321
+ """
322
+ addrs = []
323
+ ips = []
324
+ nets = []
325
+
326
+ # split IP addresses and networks
327
+ for ip in addresses:
328
+ if isinstance(ip, _BaseAddress):
329
+ if ips and ips[-1]._version != ip._version:
330
+ raise TypeError("%s and %s are not of the same version" % (
331
+ ip, ips[-1]))
332
+ ips.append(ip)
333
+ elif ip._prefixlen == ip._max_prefixlen:
334
+ if ips and ips[-1]._version != ip._version:
335
+ raise TypeError("%s and %s are not of the same version" % (
336
+ ip, ips[-1]))
337
+ try:
338
+ ips.append(ip.ip)
339
+ except AttributeError:
340
+ ips.append(ip.network_address)
341
+ else:
342
+ if nets and nets[-1]._version != ip._version:
343
+ raise TypeError("%s and %s are not of the same version" % (
344
+ ip, nets[-1]))
345
+ nets.append(ip)
346
+
347
+ # sort and dedup
348
+ ips = sorted(set(ips))
349
+
350
+ # find consecutive address ranges in the sorted sequence and summarize them
351
+ if ips:
352
+ for first, last in _find_address_range(ips):
353
+ addrs.extend(summarize_address_range(first, last))
354
+
355
+ return _collapse_addresses_internal(addrs + nets)
356
+
357
+
358
+ def get_mixed_type_key(obj):
359
+ """Return a key suitable for sorting between networks and addresses.
360
+
361
+ Address and Network objects are not sortable by default; they're
362
+ fundamentally different so the expression
363
+
364
+ IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
365
+
366
+ doesn't make any sense. There are some times however, where you may wish
367
+ to have ipaddress sort these for you anyway. If you need to do this, you
368
+ can use this function as the key= argument to sorted().
369
+
370
+ Args:
371
+ obj: either a Network or Address object.
372
+ Returns:
373
+ appropriate key.
374
+
375
+ """
376
+ if isinstance(obj, _BaseNetwork):
377
+ return obj._get_networks_key()
378
+ elif isinstance(obj, _BaseAddress):
379
+ return obj._get_address_key()
380
+ return NotImplemented
381
+
382
+
383
+ class _IPAddressBase:
384
+
385
+ """The mother class."""
386
+
387
+ __slots__ = ()
388
+
389
+ @property
390
+ def exploded(self):
391
+ """Return the longhand version of the IP address as a string."""
392
+ return self._explode_shorthand_ip_string()
393
+
394
+ @property
395
+ def compressed(self):
396
+ """Return the shorthand version of the IP address as a string."""
397
+ return str(self)
398
+
399
+ @property
400
+ def reverse_pointer(self):
401
+ """The name of the reverse DNS pointer for the IP address, e.g.:
402
+ >>> ipaddress.ip_address("127.0.0.1").reverse_pointer
403
+ '1.0.0.127.in-addr.arpa'
404
+ >>> ipaddress.ip_address("2001:db8::1").reverse_pointer
405
+ '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa'
406
+
407
+ """
408
+ return self._reverse_pointer()
409
+
410
+ @property
411
+ def version(self):
412
+ msg = '%200s has no version specified' % (type(self),)
413
+ raise NotImplementedError(msg)
414
+
415
+ def _check_int_address(self, address):
416
+ if address < 0:
417
+ msg = "%d (< 0) is not permitted as an IPv%d address"
418
+ raise AddressValueError(msg % (address, self._version))
419
+ if address > self._ALL_ONES:
420
+ msg = "%d (>= 2**%d) is not permitted as an IPv%d address"
421
+ raise AddressValueError(msg % (address, self._max_prefixlen,
422
+ self._version))
423
+
424
+ def _check_packed_address(self, address, expected_len):
425
+ address_len = len(address)
426
+ if address_len != expected_len:
427
+ msg = "%r (len %d != %d) is not permitted as an IPv%d address"
428
+ raise AddressValueError(msg % (address, address_len,
429
+ expected_len, self._version))
430
+
431
+ @classmethod
432
+ def _ip_int_from_prefix(cls, prefixlen):
433
+ """Turn the prefix length into a bitwise netmask
434
+
435
+ Args:
436
+ prefixlen: An integer, the prefix length.
437
+
438
+ Returns:
439
+ An integer.
440
+
441
+ """
442
+ return cls._ALL_ONES ^ (cls._ALL_ONES >> prefixlen)
443
+
444
+ @classmethod
445
+ def _prefix_from_ip_int(cls, ip_int):
446
+ """Return prefix length from the bitwise netmask.
447
+
448
+ Args:
449
+ ip_int: An integer, the netmask in expanded bitwise format
450
+
451
+ Returns:
452
+ An integer, the prefix length.
453
+
454
+ Raises:
455
+ ValueError: If the input intermingles zeroes & ones
456
+ """
457
+ trailing_zeroes = _count_righthand_zero_bits(ip_int,
458
+ cls._max_prefixlen)
459
+ prefixlen = cls._max_prefixlen - trailing_zeroes
460
+ leading_ones = ip_int >> trailing_zeroes
461
+ all_ones = (1 << prefixlen) - 1
462
+ if leading_ones != all_ones:
463
+ byteslen = cls._max_prefixlen // 8
464
+ details = ip_int.to_bytes(byteslen, 'big')
465
+ msg = 'Netmask pattern %r mixes zeroes & ones'
466
+ raise ValueError(msg % details)
467
+ return prefixlen
468
+
469
+ @classmethod
470
+ def _report_invalid_netmask(cls, netmask_str):
471
+ msg = '%r is not a valid netmask' % netmask_str
472
+ raise NetmaskValueError(msg) from None
473
+
474
+ @classmethod
475
+ def _prefix_from_prefix_string(cls, prefixlen_str):
476
+ """Return prefix length from a numeric string
477
+
478
+ Args:
479
+ prefixlen_str: The string to be converted
480
+
481
+ Returns:
482
+ An integer, the prefix length.
483
+
484
+ Raises:
485
+ NetmaskValueError: If the input is not a valid netmask
486
+ """
487
+ # int allows a leading +/- as well as surrounding whitespace,
488
+ # so we ensure that isn't the case
489
+ if not (prefixlen_str.isascii() and prefixlen_str.isdigit()):
490
+ cls._report_invalid_netmask(prefixlen_str)
491
+ try:
492
+ prefixlen = int(prefixlen_str)
493
+ except ValueError:
494
+ cls._report_invalid_netmask(prefixlen_str)
495
+ if not (0 <= prefixlen <= cls._max_prefixlen):
496
+ cls._report_invalid_netmask(prefixlen_str)
497
+ return prefixlen
498
+
499
+ @classmethod
500
+ def _prefix_from_ip_string(cls, ip_str):
501
+ """Turn a netmask/hostmask string into a prefix length
502
+
503
+ Args:
504
+ ip_str: The netmask/hostmask to be converted
505
+
506
+ Returns:
507
+ An integer, the prefix length.
508
+
509
+ Raises:
510
+ NetmaskValueError: If the input is not a valid netmask/hostmask
511
+ """
512
+ # Parse the netmask/hostmask like an IP address.
513
+ try:
514
+ ip_int = cls._ip_int_from_string(ip_str)
515
+ except AddressValueError:
516
+ cls._report_invalid_netmask(ip_str)
517
+
518
+ # Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
519
+ # Note that the two ambiguous cases (all-ones and all-zeroes) are
520
+ # treated as netmasks.
521
+ try:
522
+ return cls._prefix_from_ip_int(ip_int)
523
+ except ValueError:
524
+ pass
525
+
526
+ # Invert the bits, and try matching a /0+1+/ hostmask instead.
527
+ ip_int ^= cls._ALL_ONES
528
+ try:
529
+ return cls._prefix_from_ip_int(ip_int)
530
+ except ValueError:
531
+ cls._report_invalid_netmask(ip_str)
532
+
533
+ @classmethod
534
+ def _split_addr_prefix(cls, address):
535
+ """Helper function to parse address of Network/Interface.
536
+
537
+ Arg:
538
+ address: Argument of Network/Interface.
539
+
540
+ Returns:
541
+ (addr, prefix) tuple.
542
+ """
543
+ # a packed address or integer
544
+ if isinstance(address, (bytes, int)):
545
+ return address, cls._max_prefixlen
546
+
547
+ if not isinstance(address, tuple):
548
+ # Assume input argument to be string or any object representation
549
+ # which converts into a formatted IP prefix string.
550
+ address = _split_optional_netmask(address)
551
+
552
+ # Constructing from a tuple (addr, [mask])
553
+ if len(address) > 1:
554
+ return address
555
+ return address[0], cls._max_prefixlen
556
+
557
+ def __reduce__(self):
558
+ return self.__class__, (str(self),)
559
+
560
+
561
+ _address_fmt_re = None
562
+
563
+ @functools.total_ordering
564
+ class _BaseAddress(_IPAddressBase):
565
+
566
+ """A generic IP object.
567
+
568
+ This IP class contains the version independent methods which are
569
+ used by single IP addresses.
570
+ """
571
+
572
+ __slots__ = ()
573
+
574
+ def __int__(self):
575
+ return self._ip
576
+
577
+ def __eq__(self, other):
578
+ try:
579
+ return (self._ip == other._ip
580
+ and self._version == other._version)
581
+ except AttributeError:
582
+ return NotImplemented
583
+
584
+ def __lt__(self, other):
585
+ if not isinstance(other, _BaseAddress):
586
+ return NotImplemented
587
+ if self._version != other._version:
588
+ raise TypeError('%s and %s are not of the same version' % (
589
+ self, other))
590
+ if self._ip != other._ip:
591
+ return self._ip < other._ip
592
+ return False
593
+
594
+ # Shorthand for Integer addition and subtraction. This is not
595
+ # meant to ever support addition/subtraction of addresses.
596
+ def __add__(self, other):
597
+ if not isinstance(other, int):
598
+ return NotImplemented
599
+ return self.__class__(int(self) + other)
600
+
601
+ def __sub__(self, other):
602
+ if not isinstance(other, int):
603
+ return NotImplemented
604
+ return self.__class__(int(self) - other)
605
+
606
+ def __repr__(self):
607
+ return '%s(%r)' % (self.__class__.__name__, str(self))
608
+
609
+ def __str__(self):
610
+ return str(self._string_from_ip_int(self._ip))
611
+
612
+ def __hash__(self):
613
+ return hash(hex(int(self._ip)))
614
+
615
+ def _get_address_key(self):
616
+ return (self._version, self)
617
+
618
+ def __reduce__(self):
619
+ return self.__class__, (self._ip,)
620
+
621
+ def __format__(self, fmt):
622
+ """Returns an IP address as a formatted string.
623
+
624
+ Supported presentation types are:
625
+ 's': returns the IP address as a string (default)
626
+ 'b': converts to binary and returns a zero-padded string
627
+ 'X' or 'x': converts to upper- or lower-case hex and returns a zero-padded string
628
+ 'n': the same as 'b' for IPv4 and 'x' for IPv6
629
+
630
+ For binary and hex presentation types, the alternate form specifier
631
+ '#' and the grouping option '_' are supported.
632
+ """
633
+
634
+ # Support string formatting
635
+ if not fmt or fmt[-1] == 's':
636
+ return format(str(self), fmt)
637
+
638
+ # From here on down, support for 'bnXx'
639
+ global _address_fmt_re
640
+ if _address_fmt_re is None:
641
+ import re
642
+ _address_fmt_re = re.compile('(#?)(_?)([xbnX])')
643
+
644
+ m = _address_fmt_re.fullmatch(fmt)
645
+ if not m:
646
+ return super().__format__(fmt)
647
+
648
+ alternate, grouping, fmt_base = m.groups()
649
+
650
+ # Set some defaults
651
+ if fmt_base == 'n':
652
+ if self._version == 4:
653
+ fmt_base = 'b' # Binary is default for ipv4
654
+ else:
655
+ fmt_base = 'x' # Hex is default for ipv6
656
+
657
+ if fmt_base == 'b':
658
+ padlen = self._max_prefixlen
659
+ else:
660
+ padlen = self._max_prefixlen // 4
661
+
662
+ if grouping:
663
+ padlen += padlen // 4 - 1
664
+
665
+ if alternate:
666
+ padlen += 2 # 0b or 0x
667
+
668
+ return format(int(self), f'{alternate}0{padlen}{grouping}{fmt_base}')
669
+
670
+
671
+ @functools.total_ordering
672
+ class _BaseNetwork(_IPAddressBase):
673
+ """A generic IP network object.
674
+
675
+ This IP class contains the version independent methods which are
676
+ used by networks.
677
+ """
678
+
679
+ def __repr__(self):
680
+ return '%s(%r)' % (self.__class__.__name__, str(self))
681
+
682
+ def __str__(self):
683
+ return '%s/%d' % (self.network_address, self.prefixlen)
684
+
685
+ def hosts(self):
686
+ """Generate Iterator over usable hosts in a network.
687
+
688
+ This is like __iter__ except it doesn't return the network
689
+ or broadcast addresses.
690
+
691
+ """
692
+ network = int(self.network_address)
693
+ broadcast = int(self.broadcast_address)
694
+ for x in range(network + 1, broadcast):
695
+ yield self._address_class(x)
696
+
697
+ def __iter__(self):
698
+ network = int(self.network_address)
699
+ broadcast = int(self.broadcast_address)
700
+ for x in range(network, broadcast + 1):
701
+ yield self._address_class(x)
702
+
703
+ def __getitem__(self, n):
704
+ network = int(self.network_address)
705
+ broadcast = int(self.broadcast_address)
706
+ if n >= 0:
707
+ if network + n > broadcast:
708
+ raise IndexError('address out of range')
709
+ return self._address_class(network + n)
710
+ else:
711
+ n += 1
712
+ if broadcast + n < network:
713
+ raise IndexError('address out of range')
714
+ return self._address_class(broadcast + n)
715
+
716
+ def __lt__(self, other):
717
+ if not isinstance(other, _BaseNetwork):
718
+ return NotImplemented
719
+ if self._version != other._version:
720
+ raise TypeError('%s and %s are not of the same version' % (
721
+ self, other))
722
+ if self.network_address != other.network_address:
723
+ return self.network_address < other.network_address
724
+ if self.netmask != other.netmask:
725
+ return self.netmask < other.netmask
726
+ return False
727
+
728
+ def __eq__(self, other):
729
+ try:
730
+ return (self._version == other._version and
731
+ self.network_address == other.network_address and
732
+ int(self.netmask) == int(other.netmask))
733
+ except AttributeError:
734
+ return NotImplemented
735
+
736
+ def __hash__(self):
737
+ return hash((int(self.network_address), int(self.netmask)))
738
+
739
+ def __contains__(self, other):
740
+ # always false if one is v4 and the other is v6.
741
+ if self._version != other._version:
742
+ return False
743
+ # dealing with another network.
744
+ if isinstance(other, _BaseNetwork):
745
+ return False
746
+ # dealing with another address
747
+ else:
748
+ # address
749
+ return other._ip & self.netmask._ip == self.network_address._ip
750
+
751
+ def overlaps(self, other):
752
+ """Tell if self is partly contained in other."""
753
+ return self.network_address in other or (
754
+ self.broadcast_address in other or (
755
+ other.network_address in self or (
756
+ other.broadcast_address in self)))
757
+
758
+ @functools.cached_property
759
+ def broadcast_address(self):
760
+ return self._address_class(int(self.network_address) |
761
+ int(self.hostmask))
762
+
763
+ @functools.cached_property
764
+ def hostmask(self):
765
+ return self._address_class(int(self.netmask) ^ self._ALL_ONES)
766
+
767
+ @property
768
+ def with_prefixlen(self):
769
+ return '%s/%d' % (self.network_address, self._prefixlen)
770
+
771
+ @property
772
+ def with_netmask(self):
773
+ return '%s/%s' % (self.network_address, self.netmask)
774
+
775
+ @property
776
+ def with_hostmask(self):
777
+ return '%s/%s' % (self.network_address, self.hostmask)
778
+
779
+ @property
780
+ def num_addresses(self):
781
+ """Number of hosts in the current subnet."""
782
+ return int(self.broadcast_address) - int(self.network_address) + 1
783
+
784
+ @property
785
+ def _address_class(self):
786
+ # Returning bare address objects (rather than interfaces) allows for
787
+ # more consistent behaviour across the network address, broadcast
788
+ # address and individual host addresses.
789
+ msg = '%200s has no associated address class' % (type(self),)
790
+ raise NotImplementedError(msg)
791
+
792
+ @property
793
+ def prefixlen(self):
794
+ return self._prefixlen
795
+
796
+ def address_exclude(self, other):
797
+ """Remove an address from a larger block.
798
+
799
+ For example:
800
+
801
+ addr1 = ip_network('192.0.2.0/28')
802
+ addr2 = ip_network('192.0.2.1/32')
803
+ list(addr1.address_exclude(addr2)) =
804
+ [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
805
+ IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
806
+
807
+ or IPv6:
808
+
809
+ addr1 = ip_network('2001:db8::1/32')
810
+ addr2 = ip_network('2001:db8::1/128')
811
+ list(addr1.address_exclude(addr2)) =
812
+ [ip_network('2001:db8::1/128'),
813
+ ip_network('2001:db8::2/127'),
814
+ ip_network('2001:db8::4/126'),
815
+ ip_network('2001:db8::8/125'),
816
+ ...
817
+ ip_network('2001:db8:8000::/33')]
818
+
819
+ Args:
820
+ other: An IPv4Network or IPv6Network object of the same type.
821
+
822
+ Returns:
823
+ An iterator of the IPv(4|6)Network objects which is self
824
+ minus other.
825
+
826
+ Raises:
827
+ TypeError: If self and other are of differing address
828
+ versions, or if other is not a network object.
829
+ ValueError: If other is not completely contained by self.
830
+
831
+ """
832
+ if not self._version == other._version:
833
+ raise TypeError("%s and %s are not of the same version" % (
834
+ self, other))
835
+
836
+ if not isinstance(other, _BaseNetwork):
837
+ raise TypeError("%s is not a network object" % other)
838
+
839
+ if not other.subnet_of(self):
840
+ raise ValueError('%s not contained in %s' % (other, self))
841
+ if other == self:
842
+ return
843
+
844
+ # Make sure we're comparing the network of other.
845
+ other = other.__class__('%s/%s' % (other.network_address,
846
+ other.prefixlen))
847
+
848
+ s1, s2 = self.subnets()
849
+ while s1 != other and s2 != other:
850
+ if other.subnet_of(s1):
851
+ yield s2
852
+ s1, s2 = s1.subnets()
853
+ elif other.subnet_of(s2):
854
+ yield s1
855
+ s1, s2 = s2.subnets()
856
+ else:
857
+ # If we got here, there's a bug somewhere.
858
+ raise AssertionError('Error performing exclusion: '
859
+ 's1: %s s2: %s other: %s' %
860
+ (s1, s2, other))
861
+ if s1 == other:
862
+ yield s2
863
+ elif s2 == other:
864
+ yield s1
865
+ else:
866
+ # If we got here, there's a bug somewhere.
867
+ raise AssertionError('Error performing exclusion: '
868
+ 's1: %s s2: %s other: %s' %
869
+ (s1, s2, other))
870
+
871
+ def compare_networks(self, other):
872
+ """Compare two IP objects.
873
+
874
+ This is only concerned about the comparison of the integer
875
+ representation of the network addresses. This means that the
876
+ host bits aren't considered at all in this method. If you want
877
+ to compare host bits, you can easily enough do a
878
+ 'HostA._ip < HostB._ip'
879
+
880
+ Args:
881
+ other: An IP object.
882
+
883
+ Returns:
884
+ If the IP versions of self and other are the same, returns:
885
+
886
+ -1 if self < other:
887
+ eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
888
+ IPv6Network('2001:db8::1000/124') <
889
+ IPv6Network('2001:db8::2000/124')
890
+ 0 if self == other
891
+ eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
892
+ IPv6Network('2001:db8::1000/124') ==
893
+ IPv6Network('2001:db8::1000/124')
894
+ 1 if self > other
895
+ eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
896
+ IPv6Network('2001:db8::2000/124') >
897
+ IPv6Network('2001:db8::1000/124')
898
+
899
+ Raises:
900
+ TypeError if the IP versions are different.
901
+
902
+ """
903
+ # does this need to raise a ValueError?
904
+ if self._version != other._version:
905
+ raise TypeError('%s and %s are not of the same type' % (
906
+ self, other))
907
+ # self._version == other._version below here:
908
+ if self.network_address < other.network_address:
909
+ return -1
910
+ if self.network_address > other.network_address:
911
+ return 1
912
+ # self.network_address == other.network_address below here:
913
+ if self.netmask < other.netmask:
914
+ return -1
915
+ if self.netmask > other.netmask:
916
+ return 1
917
+ return 0
918
+
919
+ def _get_networks_key(self):
920
+ """Network-only key function.
921
+
922
+ Returns an object that identifies this address' network and
923
+ netmask. This function is a suitable "key" argument for sorted()
924
+ and list.sort().
925
+
926
+ """
927
+ return (self._version, self.network_address, self.netmask)
928
+
929
+ def subnets(self, prefixlen_diff=1, new_prefix=None):
930
+ """The subnets which join to make the current subnet.
931
+
932
+ In the case that self contains only one IP
933
+ (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
934
+ for IPv6), yield an iterator with just ourself.
935
+
936
+ Args:
937
+ prefixlen_diff: An integer, the amount the prefix length
938
+ should be increased by. This should not be set if
939
+ new_prefix is also set.
940
+ new_prefix: The desired new prefix length. This must be a
941
+ larger number (smaller prefix) than the existing prefix.
942
+ This should not be set if prefixlen_diff is also set.
943
+
944
+ Returns:
945
+ An iterator of IPv(4|6) objects.
946
+
947
+ Raises:
948
+ ValueError: The prefixlen_diff is too small or too large.
949
+ OR
950
+ prefixlen_diff and new_prefix are both set or new_prefix
951
+ is a smaller number than the current prefix (smaller
952
+ number means a larger network)
953
+
954
+ """
955
+ if self._prefixlen == self._max_prefixlen:
956
+ yield self
957
+ return
958
+
959
+ if new_prefix is not None:
960
+ if new_prefix < self._prefixlen:
961
+ raise ValueError('new prefix must be longer')
962
+ if prefixlen_diff != 1:
963
+ raise ValueError('cannot set prefixlen_diff and new_prefix')
964
+ prefixlen_diff = new_prefix - self._prefixlen
965
+
966
+ if prefixlen_diff < 0:
967
+ raise ValueError('prefix length diff must be > 0')
968
+ new_prefixlen = self._prefixlen + prefixlen_diff
969
+
970
+ if new_prefixlen > self._max_prefixlen:
971
+ raise ValueError(
972
+ 'prefix length diff %d is invalid for netblock %s' % (
973
+ new_prefixlen, self))
974
+
975
+ start = int(self.network_address)
976
+ end = int(self.broadcast_address) + 1
977
+ step = (int(self.hostmask) + 1) >> prefixlen_diff
978
+ for new_addr in range(start, end, step):
979
+ current = self.__class__((new_addr, new_prefixlen))
980
+ yield current
981
+
982
+ def supernet(self, prefixlen_diff=1, new_prefix=None):
983
+ """The supernet containing the current network.
984
+
985
+ Args:
986
+ prefixlen_diff: An integer, the amount the prefix length of
987
+ the network should be decreased by. For example, given a
988
+ /24 network and a prefixlen_diff of 3, a supernet with a
989
+ /21 netmask is returned.
990
+
991
+ Returns:
992
+ An IPv4 network object.
993
+
994
+ Raises:
995
+ ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
996
+ a negative prefix length.
997
+ OR
998
+ If prefixlen_diff and new_prefix are both set or new_prefix is a
999
+ larger number than the current prefix (larger number means a
1000
+ smaller network)
1001
+
1002
+ """
1003
+ if self._prefixlen == 0:
1004
+ return self
1005
+
1006
+ if new_prefix is not None:
1007
+ if new_prefix > self._prefixlen:
1008
+ raise ValueError('new prefix must be shorter')
1009
+ if prefixlen_diff != 1:
1010
+ raise ValueError('cannot set prefixlen_diff and new_prefix')
1011
+ prefixlen_diff = self._prefixlen - new_prefix
1012
+
1013
+ new_prefixlen = self.prefixlen - prefixlen_diff
1014
+ if new_prefixlen < 0:
1015
+ raise ValueError(
1016
+ 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
1017
+ (self.prefixlen, prefixlen_diff))
1018
+ return self.__class__((
1019
+ int(self.network_address) & (int(self.netmask) << prefixlen_diff),
1020
+ new_prefixlen
1021
+ ))
1022
+
1023
+ @property
1024
+ def is_multicast(self):
1025
+ """Test if the address is reserved for multicast use.
1026
+
1027
+ Returns:
1028
+ A boolean, True if the address is a multicast address.
1029
+ See RFC 2373 2.7 for details.
1030
+
1031
+ """
1032
+ return (self.network_address.is_multicast and
1033
+ self.broadcast_address.is_multicast)
1034
+
1035
+ @staticmethod
1036
+ def _is_subnet_of(a, b):
1037
+ try:
1038
+ # Always false if one is v4 and the other is v6.
1039
+ if a._version != b._version:
1040
+ raise TypeError(f"{a} and {b} are not of the same version")
1041
+ return (b.network_address <= a.network_address and
1042
+ b.broadcast_address >= a.broadcast_address)
1043
+ except AttributeError:
1044
+ raise TypeError(f"Unable to test subnet containment "
1045
+ f"between {a} and {b}")
1046
+
1047
+ def subnet_of(self, other):
1048
+ """Return True if this network is a subnet of other."""
1049
+ return self._is_subnet_of(self, other)
1050
+
1051
+ def supernet_of(self, other):
1052
+ """Return True if this network is a supernet of other."""
1053
+ return self._is_subnet_of(other, self)
1054
+
1055
+ @property
1056
+ def is_reserved(self):
1057
+ """Test if the address is otherwise IETF reserved.
1058
+
1059
+ Returns:
1060
+ A boolean, True if the address is within one of the
1061
+ reserved IPv6 Network ranges.
1062
+
1063
+ """
1064
+ return (self.network_address.is_reserved and
1065
+ self.broadcast_address.is_reserved)
1066
+
1067
+ @property
1068
+ def is_link_local(self):
1069
+ """Test if the address is reserved for link-local.
1070
+
1071
+ Returns:
1072
+ A boolean, True if the address is reserved per RFC 4291.
1073
+
1074
+ """
1075
+ return (self.network_address.is_link_local and
1076
+ self.broadcast_address.is_link_local)
1077
+
1078
+ @property
1079
+ def is_private(self):
1080
+ """Test if this network belongs to a private range.
1081
+
1082
+ Returns:
1083
+ A boolean, True if the network is reserved per
1084
+ iana-ipv4-special-registry or iana-ipv6-special-registry.
1085
+
1086
+ """
1087
+ return any(self.network_address in priv_network and
1088
+ self.broadcast_address in priv_network
1089
+ for priv_network in self._constants._private_networks) and all(
1090
+ self.network_address not in network and
1091
+ self.broadcast_address not in network
1092
+ for network in self._constants._private_networks_exceptions
1093
+ )
1094
+
1095
+ @property
1096
+ def is_global(self):
1097
+ """Test if this address is allocated for public networks.
1098
+
1099
+ Returns:
1100
+ A boolean, True if the address is not reserved per
1101
+ iana-ipv4-special-registry or iana-ipv6-special-registry.
1102
+
1103
+ """
1104
+ return not self.is_private
1105
+
1106
+ @property
1107
+ def is_unspecified(self):
1108
+ """Test if the address is unspecified.
1109
+
1110
+ Returns:
1111
+ A boolean, True if this is the unspecified address as defined in
1112
+ RFC 2373 2.5.2.
1113
+
1114
+ """
1115
+ return (self.network_address.is_unspecified and
1116
+ self.broadcast_address.is_unspecified)
1117
+
1118
+ @property
1119
+ def is_loopback(self):
1120
+ """Test if the address is a loopback address.
1121
+
1122
+ Returns:
1123
+ A boolean, True if the address is a loopback address as defined in
1124
+ RFC 2373 2.5.3.
1125
+
1126
+ """
1127
+ return (self.network_address.is_loopback and
1128
+ self.broadcast_address.is_loopback)
1129
+
1130
+
1131
+ class _BaseConstants:
1132
+
1133
+ _private_networks = []
1134
+
1135
+
1136
+ _BaseNetwork._constants = _BaseConstants
1137
+
1138
+
1139
+ class _BaseV4:
1140
+
1141
+ """Base IPv4 object.
1142
+
1143
+ The following methods are used by IPv4 objects in both single IP
1144
+ addresses and networks.
1145
+
1146
+ """
1147
+
1148
+ __slots__ = ()
1149
+ _version = 4
1150
+ # Equivalent to 255.255.255.255 or 32 bits of 1's.
1151
+ _ALL_ONES = (2**IPV4LENGTH) - 1
1152
+
1153
+ _max_prefixlen = IPV4LENGTH
1154
+ # There are only a handful of valid v4 netmasks, so we cache them all
1155
+ # when constructed (see _make_netmask()).
1156
+ _netmask_cache = {}
1157
+
1158
+ def _explode_shorthand_ip_string(self):
1159
+ return str(self)
1160
+
1161
+ @classmethod
1162
+ def _make_netmask(cls, arg):
1163
+ """Make a (netmask, prefix_len) tuple from the given argument.
1164
+
1165
+ Argument can be:
1166
+ - an integer (the prefix length)
1167
+ - a string representing the prefix length (e.g. "24")
1168
+ - a string representing the prefix netmask (e.g. "255.255.255.0")
1169
+ """
1170
+ if arg not in cls._netmask_cache:
1171
+ if isinstance(arg, int):
1172
+ prefixlen = arg
1173
+ if not (0 <= prefixlen <= cls._max_prefixlen):
1174
+ cls._report_invalid_netmask(prefixlen)
1175
+ else:
1176
+ try:
1177
+ # Check for a netmask in prefix length form
1178
+ prefixlen = cls._prefix_from_prefix_string(arg)
1179
+ except NetmaskValueError:
1180
+ # Check for a netmask or hostmask in dotted-quad form.
1181
+ # This may raise NetmaskValueError.
1182
+ prefixlen = cls._prefix_from_ip_string(arg)
1183
+ netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))
1184
+ cls._netmask_cache[arg] = netmask, prefixlen
1185
+ return cls._netmask_cache[arg]
1186
+
1187
+ @classmethod
1188
+ def _ip_int_from_string(cls, ip_str):
1189
+ """Turn the given IP string into an integer for comparison.
1190
+
1191
+ Args:
1192
+ ip_str: A string, the IP ip_str.
1193
+
1194
+ Returns:
1195
+ The IP ip_str as an integer.
1196
+
1197
+ Raises:
1198
+ AddressValueError: if ip_str isn't a valid IPv4 Address.
1199
+
1200
+ """
1201
+ if not ip_str:
1202
+ raise AddressValueError('Address cannot be empty')
1203
+
1204
+ octets = ip_str.split('.')
1205
+ if len(octets) != 4:
1206
+ raise AddressValueError("Expected 4 octets in %r" % ip_str)
1207
+
1208
+ try:
1209
+ return int.from_bytes(map(cls._parse_octet, octets), 'big')
1210
+ except ValueError as exc:
1211
+ raise AddressValueError("%s in %r" % (exc, ip_str)) from None
1212
+
1213
+ @classmethod
1214
+ def _parse_octet(cls, octet_str):
1215
+ """Convert a decimal octet into an integer.
1216
+
1217
+ Args:
1218
+ octet_str: A string, the number to parse.
1219
+
1220
+ Returns:
1221
+ The octet as an integer.
1222
+
1223
+ Raises:
1224
+ ValueError: if the octet isn't strictly a decimal from [0..255].
1225
+
1226
+ """
1227
+ if not octet_str:
1228
+ raise ValueError("Empty octet not permitted")
1229
+ # Reject non-ASCII digits.
1230
+ if not (octet_str.isascii() and octet_str.isdigit()):
1231
+ msg = "Only decimal digits permitted in %r"
1232
+ raise ValueError(msg % octet_str)
1233
+ # We do the length check second, since the invalid character error
1234
+ # is likely to be more informative for the user
1235
+ if len(octet_str) > 3:
1236
+ msg = "At most 3 characters permitted in %r"
1237
+ raise ValueError(msg % octet_str)
1238
+ # Handle leading zeros as strict as glibc's inet_pton()
1239
+ # See security bug bpo-36384
1240
+ if octet_str != '0' and octet_str[0] == '0':
1241
+ msg = "Leading zeros are not permitted in %r"
1242
+ raise ValueError(msg % octet_str)
1243
+ # Convert to integer (we know digits are legal)
1244
+ octet_int = int(octet_str, 10)
1245
+ if octet_int > 255:
1246
+ raise ValueError("Octet %d (> 255) not permitted" % octet_int)
1247
+ return octet_int
1248
+
1249
+ @classmethod
1250
+ def _string_from_ip_int(cls, ip_int):
1251
+ """Turns a 32-bit integer into dotted decimal notation.
1252
+
1253
+ Args:
1254
+ ip_int: An integer, the IP address.
1255
+
1256
+ Returns:
1257
+ The IP address as a string in dotted decimal notation.
1258
+
1259
+ """
1260
+ return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
1261
+
1262
+ def _reverse_pointer(self):
1263
+ """Return the reverse DNS pointer name for the IPv4 address.
1264
+
1265
+ This implements the method described in RFC1035 3.5.
1266
+
1267
+ """
1268
+ reverse_octets = str(self).split('.')[::-1]
1269
+ return '.'.join(reverse_octets) + '.in-addr.arpa'
1270
+
1271
+ @property
1272
+ def max_prefixlen(self):
1273
+ return self._max_prefixlen
1274
+
1275
+ @property
1276
+ def version(self):
1277
+ return self._version
1278
+
1279
+
1280
+ class IPv4Address(_BaseV4, _BaseAddress):
1281
+
1282
+ """Represent and manipulate single IPv4 Addresses."""
1283
+
1284
+ __slots__ = ('_ip', '__weakref__')
1285
+
1286
+ def __init__(self, address):
1287
+
1288
+ """
1289
+ Args:
1290
+ address: A string or integer representing the IP
1291
+
1292
+ Additionally, an integer can be passed, so
1293
+ IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1294
+ or, more generally
1295
+ IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1296
+ IPv4Address('192.0.2.1')
1297
+
1298
+ Raises:
1299
+ AddressValueError: If ipaddress isn't a valid IPv4 address.
1300
+
1301
+ """
1302
+ # Efficient constructor from integer.
1303
+ if isinstance(address, int):
1304
+ self._check_int_address(address)
1305
+ self._ip = address
1306
+ return
1307
+
1308
+ # Constructing from a packed address
1309
+ if isinstance(address, bytes):
1310
+ self._check_packed_address(address, 4)
1311
+ self._ip = int.from_bytes(address) # big endian
1312
+ return
1313
+
1314
+ # Assume input argument to be string or any object representation
1315
+ # which converts into a formatted IP string.
1316
+ addr_str = str(address)
1317
+ if '/' in addr_str:
1318
+ raise AddressValueError(f"Unexpected '/' in {address!r}")
1319
+ self._ip = self._ip_int_from_string(addr_str)
1320
+
1321
+ @property
1322
+ def packed(self):
1323
+ """The binary representation of this address."""
1324
+ return v4_int_to_packed(self._ip)
1325
+
1326
+ @property
1327
+ def is_reserved(self):
1328
+ """Test if the address is otherwise IETF reserved.
1329
+
1330
+ Returns:
1331
+ A boolean, True if the address is within the
1332
+ reserved IPv4 Network range.
1333
+
1334
+ """
1335
+ return self in self._constants._reserved_network
1336
+
1337
+ @property
1338
+ @functools.lru_cache()
1339
+ def is_private(self):
1340
+ """``True`` if the address is defined as not globally reachable by
1341
+ iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_
1342
+ (for IPv6) with the following exceptions:
1343
+
1344
+ * ``is_private`` is ``False`` for ``100.64.0.0/10``
1345
+ * For IPv4-mapped IPv6-addresses the ``is_private`` value is determined by the
1346
+ semantics of the underlying IPv4 addresses and the following condition holds
1347
+ (see :attr:`IPv6Address.ipv4_mapped`)::
1348
+
1349
+ address.is_private == address.ipv4_mapped.is_private
1350
+
1351
+ ``is_private`` has value opposite to :attr:`is_global`, except for the ``100.64.0.0/10``
1352
+ IPv4 range where they are both ``False``.
1353
+ """
1354
+ return (
1355
+ any(self in net for net in self._constants._private_networks)
1356
+ and all(self not in net for net in self._constants._private_networks_exceptions)
1357
+ )
1358
+
1359
+ @property
1360
+ @functools.lru_cache()
1361
+ def is_global(self):
1362
+ """``True`` if the address is defined as globally reachable by
1363
+ iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_
1364
+ (for IPv6) with the following exception:
1365
+
1366
+ For IPv4-mapped IPv6-addresses the ``is_private`` value is determined by the
1367
+ semantics of the underlying IPv4 addresses and the following condition holds
1368
+ (see :attr:`IPv6Address.ipv4_mapped`)::
1369
+
1370
+ address.is_global == address.ipv4_mapped.is_global
1371
+
1372
+ ``is_global`` has value opposite to :attr:`is_private`, except for the ``100.64.0.0/10``
1373
+ IPv4 range where they are both ``False``.
1374
+ """
1375
+ return self not in self._constants._public_network and not self.is_private
1376
+
1377
+ @property
1378
+ def is_multicast(self):
1379
+ """Test if the address is reserved for multicast use.
1380
+
1381
+ Returns:
1382
+ A boolean, True if the address is multicast.
1383
+ See RFC 3171 for details.
1384
+
1385
+ """
1386
+ return self in self._constants._multicast_network
1387
+
1388
+ @property
1389
+ def is_unspecified(self):
1390
+ """Test if the address is unspecified.
1391
+
1392
+ Returns:
1393
+ A boolean, True if this is the unspecified address as defined in
1394
+ RFC 5735 3.
1395
+
1396
+ """
1397
+ return self == self._constants._unspecified_address
1398
+
1399
+ @property
1400
+ def is_loopback(self):
1401
+ """Test if the address is a loopback address.
1402
+
1403
+ Returns:
1404
+ A boolean, True if the address is a loopback per RFC 3330.
1405
+
1406
+ """
1407
+ return self in self._constants._loopback_network
1408
+
1409
+ @property
1410
+ def is_link_local(self):
1411
+ """Test if the address is reserved for link-local.
1412
+
1413
+ Returns:
1414
+ A boolean, True if the address is link-local per RFC 3927.
1415
+
1416
+ """
1417
+ return self in self._constants._linklocal_network
1418
+
1419
+
1420
+ class IPv4Interface(IPv4Address):
1421
+
1422
+ def __init__(self, address):
1423
+ addr, mask = self._split_addr_prefix(address)
1424
+
1425
+ IPv4Address.__init__(self, addr)
1426
+ self.network = IPv4Network((addr, mask), strict=False)
1427
+ self.netmask = self.network.netmask
1428
+ self._prefixlen = self.network._prefixlen
1429
+
1430
+ @functools.cached_property
1431
+ def hostmask(self):
1432
+ return self.network.hostmask
1433
+
1434
+ def __str__(self):
1435
+ return '%s/%d' % (self._string_from_ip_int(self._ip),
1436
+ self._prefixlen)
1437
+
1438
+ def __eq__(self, other):
1439
+ address_equal = IPv4Address.__eq__(self, other)
1440
+ if address_equal is NotImplemented or not address_equal:
1441
+ return address_equal
1442
+ try:
1443
+ return self.network == other.network
1444
+ except AttributeError:
1445
+ # An interface with an associated network is NOT the
1446
+ # same as an unassociated address. That's why the hash
1447
+ # takes the extra info into account.
1448
+ return False
1449
+
1450
+ def __lt__(self, other):
1451
+ address_less = IPv4Address.__lt__(self, other)
1452
+ if address_less is NotImplemented:
1453
+ return NotImplemented
1454
+ try:
1455
+ return (self.network < other.network or
1456
+ self.network == other.network and address_less)
1457
+ except AttributeError:
1458
+ # We *do* allow addresses and interfaces to be sorted. The
1459
+ # unassociated address is considered less than all interfaces.
1460
+ return False
1461
+
1462
+ def __hash__(self):
1463
+ return hash((self._ip, self._prefixlen, int(self.network.network_address)))
1464
+
1465
+ __reduce__ = _IPAddressBase.__reduce__
1466
+
1467
+ @property
1468
+ def ip(self):
1469
+ return IPv4Address(self._ip)
1470
+
1471
+ @property
1472
+ def with_prefixlen(self):
1473
+ return '%s/%s' % (self._string_from_ip_int(self._ip),
1474
+ self._prefixlen)
1475
+
1476
+ @property
1477
+ def with_netmask(self):
1478
+ return '%s/%s' % (self._string_from_ip_int(self._ip),
1479
+ self.netmask)
1480
+
1481
+ @property
1482
+ def with_hostmask(self):
1483
+ return '%s/%s' % (self._string_from_ip_int(self._ip),
1484
+ self.hostmask)
1485
+
1486
+
1487
+ class IPv4Network(_BaseV4, _BaseNetwork):
1488
+
1489
+ """This class represents and manipulates 32-bit IPv4 network + addresses..
1490
+
1491
+ Attributes: [examples for IPv4Network('192.0.2.0/27')]
1492
+ .network_address: IPv4Address('192.0.2.0')
1493
+ .hostmask: IPv4Address('0.0.0.31')
1494
+ .broadcast_address: IPv4Address('192.0.2.32')
1495
+ .netmask: IPv4Address('255.255.255.224')
1496
+ .prefixlen: 27
1497
+
1498
+ """
1499
+ # Class to use when creating address objects
1500
+ _address_class = IPv4Address
1501
+
1502
+ def __init__(self, address, strict=True):
1503
+ """Instantiate a new IPv4 network object.
1504
+
1505
+ Args:
1506
+ address: A string or integer representing the IP [& network].
1507
+ '192.0.2.0/24'
1508
+ '192.0.2.0/255.255.255.0'
1509
+ '192.0.2.0/0.0.0.255'
1510
+ are all functionally the same in IPv4. Similarly,
1511
+ '192.0.2.1'
1512
+ '192.0.2.1/255.255.255.255'
1513
+ '192.0.2.1/32'
1514
+ are also functionally equivalent. That is to say, failing to
1515
+ provide a subnetmask will create an object with a mask of /32.
1516
+
1517
+ If the mask (portion after the / in the argument) is given in
1518
+ dotted quad form, it is treated as a netmask if it starts with a
1519
+ non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1520
+ starts with a zero field (e.g. 0.255.255.255 == /8), with the
1521
+ single exception of an all-zero mask which is treated as a
1522
+ netmask == /0. If no mask is given, a default of /32 is used.
1523
+
1524
+ Additionally, an integer can be passed, so
1525
+ IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1526
+ or, more generally
1527
+ IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1528
+ IPv4Interface('192.0.2.1')
1529
+
1530
+ Raises:
1531
+ AddressValueError: If ipaddress isn't a valid IPv4 address.
1532
+ NetmaskValueError: If the netmask isn't valid for
1533
+ an IPv4 address.
1534
+ ValueError: If strict is True and a network address is not
1535
+ supplied.
1536
+ """
1537
+ addr, mask = self._split_addr_prefix(address)
1538
+
1539
+ self.network_address = IPv4Address(addr)
1540
+ self.netmask, self._prefixlen = self._make_netmask(mask)
1541
+ packed = int(self.network_address)
1542
+ if packed & int(self.netmask) != packed:
1543
+ if strict:
1544
+ raise ValueError('%s has host bits set' % self)
1545
+ else:
1546
+ self.network_address = IPv4Address(packed &
1547
+ int(self.netmask))
1548
+
1549
+ if self._prefixlen == (self._max_prefixlen - 1):
1550
+ self.hosts = self.__iter__
1551
+ elif self._prefixlen == (self._max_prefixlen):
1552
+ self.hosts = lambda: [IPv4Address(addr)]
1553
+
1554
+ @property
1555
+ @functools.lru_cache()
1556
+ def is_global(self):
1557
+ """Test if this address is allocated for public networks.
1558
+
1559
+ Returns:
1560
+ A boolean, True if the address is not reserved per
1561
+ iana-ipv4-special-registry.
1562
+
1563
+ """
1564
+ return (not (self.network_address in IPv4Network('100.64.0.0/10') and
1565
+ self.broadcast_address in IPv4Network('100.64.0.0/10')) and
1566
+ not self.is_private)
1567
+
1568
+
1569
+ class _IPv4Constants:
1570
+ _linklocal_network = IPv4Network('169.254.0.0/16')
1571
+
1572
+ _loopback_network = IPv4Network('127.0.0.0/8')
1573
+
1574
+ _multicast_network = IPv4Network('224.0.0.0/4')
1575
+
1576
+ _public_network = IPv4Network('100.64.0.0/10')
1577
+
1578
+ # Not globally reachable address blocks listed on
1579
+ # https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
1580
+ _private_networks = [
1581
+ IPv4Network('0.0.0.0/8'),
1582
+ IPv4Network('10.0.0.0/8'),
1583
+ IPv4Network('127.0.0.0/8'),
1584
+ IPv4Network('169.254.0.0/16'),
1585
+ IPv4Network('172.16.0.0/12'),
1586
+ IPv4Network('192.0.0.0/24'),
1587
+ IPv4Network('192.0.0.170/31'),
1588
+ IPv4Network('192.0.2.0/24'),
1589
+ IPv4Network('192.168.0.0/16'),
1590
+ IPv4Network('198.18.0.0/15'),
1591
+ IPv4Network('198.51.100.0/24'),
1592
+ IPv4Network('203.0.113.0/24'),
1593
+ IPv4Network('240.0.0.0/4'),
1594
+ IPv4Network('255.255.255.255/32'),
1595
+ ]
1596
+
1597
+ _private_networks_exceptions = [
1598
+ IPv4Network('192.0.0.9/32'),
1599
+ IPv4Network('192.0.0.10/32'),
1600
+ ]
1601
+
1602
+ _reserved_network = IPv4Network('240.0.0.0/4')
1603
+
1604
+ _unspecified_address = IPv4Address('0.0.0.0')
1605
+
1606
+
1607
+ IPv4Address._constants = _IPv4Constants
1608
+ IPv4Network._constants = _IPv4Constants
1609
+
1610
+
1611
+ class _BaseV6:
1612
+
1613
+ """Base IPv6 object.
1614
+
1615
+ The following methods are used by IPv6 objects in both single IP
1616
+ addresses and networks.
1617
+
1618
+ """
1619
+
1620
+ __slots__ = ()
1621
+ _version = 6
1622
+ _ALL_ONES = (2**IPV6LENGTH) - 1
1623
+ _HEXTET_COUNT = 8
1624
+ _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1625
+ _max_prefixlen = IPV6LENGTH
1626
+
1627
+ # There are only a bunch of valid v6 netmasks, so we cache them all
1628
+ # when constructed (see _make_netmask()).
1629
+ _netmask_cache = {}
1630
+
1631
+ @classmethod
1632
+ def _make_netmask(cls, arg):
1633
+ """Make a (netmask, prefix_len) tuple from the given argument.
1634
+
1635
+ Argument can be:
1636
+ - an integer (the prefix length)
1637
+ - a string representing the prefix length (e.g. "24")
1638
+ - a string representing the prefix netmask (e.g. "255.255.255.0")
1639
+ """
1640
+ if arg not in cls._netmask_cache:
1641
+ if isinstance(arg, int):
1642
+ prefixlen = arg
1643
+ if not (0 <= prefixlen <= cls._max_prefixlen):
1644
+ cls._report_invalid_netmask(prefixlen)
1645
+ else:
1646
+ prefixlen = cls._prefix_from_prefix_string(arg)
1647
+ netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))
1648
+ cls._netmask_cache[arg] = netmask, prefixlen
1649
+ return cls._netmask_cache[arg]
1650
+
1651
+ @classmethod
1652
+ def _ip_int_from_string(cls, ip_str):
1653
+ """Turn an IPv6 ip_str into an integer.
1654
+
1655
+ Args:
1656
+ ip_str: A string, the IPv6 ip_str.
1657
+
1658
+ Returns:
1659
+ An int, the IPv6 address
1660
+
1661
+ Raises:
1662
+ AddressValueError: if ip_str isn't a valid IPv6 Address.
1663
+
1664
+ """
1665
+ if not ip_str:
1666
+ raise AddressValueError('Address cannot be empty')
1667
+ if len(ip_str) > 45:
1668
+ shorten = ip_str
1669
+ if len(shorten) > 100:
1670
+ shorten = f'{ip_str[:45]}({len(ip_str)-90} chars elided){ip_str[-45:]}'
1671
+ raise AddressValueError(f"At most 45 characters expected in "
1672
+ f"{shorten!r}")
1673
+
1674
+ # We want to allow more parts than the max to be 'split'
1675
+ # to preserve the correct error message when there are
1676
+ # too many parts combined with '::'
1677
+ _max_parts = cls._HEXTET_COUNT + 1
1678
+ parts = ip_str.split(':', maxsplit=_max_parts)
1679
+
1680
+ # An IPv6 address needs at least 2 colons (3 parts).
1681
+ _min_parts = 3
1682
+ if len(parts) < _min_parts:
1683
+ msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1684
+ raise AddressValueError(msg)
1685
+
1686
+ # If the address has an IPv4-style suffix, convert it to hexadecimal.
1687
+ if '.' in parts[-1]:
1688
+ try:
1689
+ ipv4_int = IPv4Address(parts.pop())._ip
1690
+ except AddressValueError as exc:
1691
+ raise AddressValueError("%s in %r" % (exc, ip_str)) from None
1692
+ parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1693
+ parts.append('%x' % (ipv4_int & 0xFFFF))
1694
+
1695
+ # An IPv6 address can't have more than 8 colons (9 parts).
1696
+ # The extra colon comes from using the "::" notation for a single
1697
+ # leading or trailing zero part.
1698
+ if len(parts) > _max_parts:
1699
+ msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1700
+ raise AddressValueError(msg)
1701
+
1702
+ # Disregarding the endpoints, find '::' with nothing in between.
1703
+ # This indicates that a run of zeroes has been skipped.
1704
+ skip_index = None
1705
+ for i in range(1, len(parts) - 1):
1706
+ if not parts[i]:
1707
+ if skip_index is not None:
1708
+ # Can't have more than one '::'
1709
+ msg = "At most one '::' permitted in %r" % ip_str
1710
+ raise AddressValueError(msg)
1711
+ skip_index = i
1712
+
1713
+ # parts_hi is the number of parts to copy from above/before the '::'
1714
+ # parts_lo is the number of parts to copy from below/after the '::'
1715
+ if skip_index is not None:
1716
+ # If we found a '::', then check if it also covers the endpoints.
1717
+ parts_hi = skip_index
1718
+ parts_lo = len(parts) - skip_index - 1
1719
+ if not parts[0]:
1720
+ parts_hi -= 1
1721
+ if parts_hi:
1722
+ msg = "Leading ':' only permitted as part of '::' in %r"
1723
+ raise AddressValueError(msg % ip_str) # ^: requires ^::
1724
+ if not parts[-1]:
1725
+ parts_lo -= 1
1726
+ if parts_lo:
1727
+ msg = "Trailing ':' only permitted as part of '::' in %r"
1728
+ raise AddressValueError(msg % ip_str) # :$ requires ::$
1729
+ parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo)
1730
+ if parts_skipped < 1:
1731
+ msg = "Expected at most %d other parts with '::' in %r"
1732
+ raise AddressValueError(msg % (cls._HEXTET_COUNT-1, ip_str))
1733
+ else:
1734
+ # Otherwise, allocate the entire address to parts_hi. The
1735
+ # endpoints could still be empty, but _parse_hextet() will check
1736
+ # for that.
1737
+ if len(parts) != cls._HEXTET_COUNT:
1738
+ msg = "Exactly %d parts expected without '::' in %r"
1739
+ raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str))
1740
+ if not parts[0]:
1741
+ msg = "Leading ':' only permitted as part of '::' in %r"
1742
+ raise AddressValueError(msg % ip_str) # ^: requires ^::
1743
+ if not parts[-1]:
1744
+ msg = "Trailing ':' only permitted as part of '::' in %r"
1745
+ raise AddressValueError(msg % ip_str) # :$ requires ::$
1746
+ parts_hi = len(parts)
1747
+ parts_lo = 0
1748
+ parts_skipped = 0
1749
+
1750
+ try:
1751
+ # Now, parse the hextets into a 128-bit integer.
1752
+ ip_int = 0
1753
+ for i in range(parts_hi):
1754
+ ip_int <<= 16
1755
+ ip_int |= cls._parse_hextet(parts[i])
1756
+ ip_int <<= 16 * parts_skipped
1757
+ for i in range(-parts_lo, 0):
1758
+ ip_int <<= 16
1759
+ ip_int |= cls._parse_hextet(parts[i])
1760
+ return ip_int
1761
+ except ValueError as exc:
1762
+ raise AddressValueError("%s in %r" % (exc, ip_str)) from None
1763
+
1764
+ @classmethod
1765
+ def _parse_hextet(cls, hextet_str):
1766
+ """Convert an IPv6 hextet string into an integer.
1767
+
1768
+ Args:
1769
+ hextet_str: A string, the number to parse.
1770
+
1771
+ Returns:
1772
+ The hextet as an integer.
1773
+
1774
+ Raises:
1775
+ ValueError: if the input isn't strictly a hex number from
1776
+ [0..FFFF].
1777
+
1778
+ """
1779
+ # Reject non-ASCII digits.
1780
+ if not cls._HEX_DIGITS.issuperset(hextet_str):
1781
+ raise ValueError("Only hex digits permitted in %r" % hextet_str)
1782
+ # We do the length check second, since the invalid character error
1783
+ # is likely to be more informative for the user
1784
+ if len(hextet_str) > 4:
1785
+ msg = "At most 4 characters permitted in %r"
1786
+ raise ValueError(msg % hextet_str)
1787
+ # Length check means we can skip checking the integer value
1788
+ return int(hextet_str, 16)
1789
+
1790
+ @classmethod
1791
+ def _compress_hextets(cls, hextets):
1792
+ """Compresses a list of hextets.
1793
+
1794
+ Compresses a list of strings, replacing the longest continuous
1795
+ sequence of "0" in the list with "" and adding empty strings at
1796
+ the beginning or at the end of the string such that subsequently
1797
+ calling ":".join(hextets) will produce the compressed version of
1798
+ the IPv6 address.
1799
+
1800
+ Args:
1801
+ hextets: A list of strings, the hextets to compress.
1802
+
1803
+ Returns:
1804
+ A list of strings.
1805
+
1806
+ """
1807
+ best_doublecolon_start = -1
1808
+ best_doublecolon_len = 0
1809
+ doublecolon_start = -1
1810
+ doublecolon_len = 0
1811
+ for index, hextet in enumerate(hextets):
1812
+ if hextet == '0':
1813
+ doublecolon_len += 1
1814
+ if doublecolon_start == -1:
1815
+ # Start of a sequence of zeros.
1816
+ doublecolon_start = index
1817
+ if doublecolon_len > best_doublecolon_len:
1818
+ # This is the longest sequence of zeros so far.
1819
+ best_doublecolon_len = doublecolon_len
1820
+ best_doublecolon_start = doublecolon_start
1821
+ else:
1822
+ doublecolon_len = 0
1823
+ doublecolon_start = -1
1824
+
1825
+ if best_doublecolon_len > 1:
1826
+ best_doublecolon_end = (best_doublecolon_start +
1827
+ best_doublecolon_len)
1828
+ # For zeros at the end of the address.
1829
+ if best_doublecolon_end == len(hextets):
1830
+ hextets += ['']
1831
+ hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1832
+ # For zeros at the beginning of the address.
1833
+ if best_doublecolon_start == 0:
1834
+ hextets = [''] + hextets
1835
+
1836
+ return hextets
1837
+
1838
+ @classmethod
1839
+ def _string_from_ip_int(cls, ip_int=None):
1840
+ """Turns a 128-bit integer into hexadecimal notation.
1841
+
1842
+ Args:
1843
+ ip_int: An integer, the IP address.
1844
+
1845
+ Returns:
1846
+ A string, the hexadecimal representation of the address.
1847
+
1848
+ Raises:
1849
+ ValueError: The address is bigger than 128 bits of all ones.
1850
+
1851
+ """
1852
+ if ip_int is None:
1853
+ ip_int = int(cls._ip)
1854
+
1855
+ if ip_int > cls._ALL_ONES:
1856
+ raise ValueError('IPv6 address is too large')
1857
+
1858
+ hex_str = '%032x' % ip_int
1859
+ hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
1860
+
1861
+ hextets = cls._compress_hextets(hextets)
1862
+ return ':'.join(hextets)
1863
+
1864
+ def _explode_shorthand_ip_string(self):
1865
+ """Expand a shortened IPv6 address.
1866
+
1867
+ Returns:
1868
+ A string, the expanded IPv6 address.
1869
+
1870
+ """
1871
+ if isinstance(self, IPv6Network):
1872
+ ip_str = str(self.network_address)
1873
+ elif isinstance(self, IPv6Interface):
1874
+ ip_str = str(self.ip)
1875
+ else:
1876
+ ip_str = str(self)
1877
+
1878
+ ip_int = self._ip_int_from_string(ip_str)
1879
+ hex_str = '%032x' % ip_int
1880
+ parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
1881
+ if isinstance(self, (_BaseNetwork, IPv6Interface)):
1882
+ return '%s/%d' % (':'.join(parts), self._prefixlen)
1883
+ return ':'.join(parts)
1884
+
1885
+ def _reverse_pointer(self):
1886
+ """Return the reverse DNS pointer name for the IPv6 address.
1887
+
1888
+ This implements the method described in RFC3596 2.5.
1889
+
1890
+ """
1891
+ reverse_chars = self.exploded[::-1].replace(':', '')
1892
+ return '.'.join(reverse_chars) + '.ip6.arpa'
1893
+
1894
+ @staticmethod
1895
+ def _split_scope_id(ip_str):
1896
+ """Helper function to parse IPv6 string address with scope id.
1897
+
1898
+ See RFC 4007 for details.
1899
+
1900
+ Args:
1901
+ ip_str: A string, the IPv6 address.
1902
+
1903
+ Returns:
1904
+ (addr, scope_id) tuple.
1905
+
1906
+ """
1907
+ addr, sep, scope_id = ip_str.partition('%')
1908
+ if not sep:
1909
+ scope_id = None
1910
+ elif not scope_id or '%' in scope_id:
1911
+ raise AddressValueError('Invalid IPv6 address: "%r"' % ip_str)
1912
+ return addr, scope_id
1913
+
1914
+ @property
1915
+ def max_prefixlen(self):
1916
+ return self._max_prefixlen
1917
+
1918
+ @property
1919
+ def version(self):
1920
+ return self._version
1921
+
1922
+
1923
+ class IPv6Address(_BaseV6, _BaseAddress):
1924
+
1925
+ """Represent and manipulate single IPv6 Addresses."""
1926
+
1927
+ __slots__ = ('_ip', '_scope_id', '__weakref__')
1928
+
1929
+ def __init__(self, address):
1930
+ """Instantiate a new IPv6 address object.
1931
+
1932
+ Args:
1933
+ address: A string or integer representing the IP
1934
+
1935
+ Additionally, an integer can be passed, so
1936
+ IPv6Address('2001:db8::') ==
1937
+ IPv6Address(42540766411282592856903984951653826560)
1938
+ or, more generally
1939
+ IPv6Address(int(IPv6Address('2001:db8::'))) ==
1940
+ IPv6Address('2001:db8::')
1941
+
1942
+ Raises:
1943
+ AddressValueError: If address isn't a valid IPv6 address.
1944
+
1945
+ """
1946
+ # Efficient constructor from integer.
1947
+ if isinstance(address, int):
1948
+ self._check_int_address(address)
1949
+ self._ip = address
1950
+ self._scope_id = None
1951
+ return
1952
+
1953
+ # Constructing from a packed address
1954
+ if isinstance(address, bytes):
1955
+ self._check_packed_address(address, 16)
1956
+ self._ip = int.from_bytes(address, 'big')
1957
+ self._scope_id = None
1958
+ return
1959
+
1960
+ # Assume input argument to be string or any object representation
1961
+ # which converts into a formatted IP string.
1962
+ addr_str = str(address)
1963
+ if '/' in addr_str:
1964
+ raise AddressValueError(f"Unexpected '/' in {address!r}")
1965
+ addr_str, self._scope_id = self._split_scope_id(addr_str)
1966
+
1967
+ self._ip = self._ip_int_from_string(addr_str)
1968
+
1969
+ def _explode_shorthand_ip_string(self):
1970
+ ipv4_mapped = self.ipv4_mapped
1971
+ if ipv4_mapped is None:
1972
+ return super()._explode_shorthand_ip_string()
1973
+ prefix_len = 30
1974
+ raw_exploded_str = super()._explode_shorthand_ip_string()
1975
+ return f"{raw_exploded_str[:prefix_len]}{ipv4_mapped!s}"
1976
+
1977
+ def _reverse_pointer(self):
1978
+ ipv4_mapped = self.ipv4_mapped
1979
+ if ipv4_mapped is None:
1980
+ return super()._reverse_pointer()
1981
+ prefix_len = 30
1982
+ raw_exploded_str = super()._explode_shorthand_ip_string()[:prefix_len]
1983
+ # ipv4 encoded using hexadecimal nibbles instead of decimals
1984
+ ipv4_int = ipv4_mapped._ip
1985
+ reverse_chars = f"{raw_exploded_str}{ipv4_int:008x}"[::-1].replace(':', '')
1986
+ return '.'.join(reverse_chars) + '.ip6.arpa'
1987
+
1988
+ def _ipv4_mapped_ipv6_to_str(self):
1989
+ """Return convenient text representation of IPv4-mapped IPv6 address
1990
+
1991
+ See RFC 4291 2.5.5.2, 2.2 p.3 for details.
1992
+
1993
+ Returns:
1994
+ A string, 'x:x:x:x:x:x:d.d.d.d', where the 'x's are the hexadecimal values of
1995
+ the six high-order 16-bit pieces of the address, and the 'd's are
1996
+ the decimal values of the four low-order 8-bit pieces of the
1997
+ address (standard IPv4 representation) as defined in RFC 4291 2.2 p.3.
1998
+
1999
+ """
2000
+ ipv4_mapped = self.ipv4_mapped
2001
+ if ipv4_mapped is None:
2002
+ raise AddressValueError("Can not apply to non-IPv4-mapped IPv6 address %s" % str(self))
2003
+ high_order_bits = self._ip >> 32
2004
+ return "%s:%s" % (self._string_from_ip_int(high_order_bits), str(ipv4_mapped))
2005
+
2006
+ def __str__(self):
2007
+ ipv4_mapped = self.ipv4_mapped
2008
+ if ipv4_mapped is None:
2009
+ ip_str = super().__str__()
2010
+ else:
2011
+ ip_str = self._ipv4_mapped_ipv6_to_str()
2012
+ return ip_str + '%' + self._scope_id if self._scope_id else ip_str
2013
+
2014
+ def __hash__(self):
2015
+ return hash((self._ip, self._scope_id))
2016
+
2017
+ def __eq__(self, other):
2018
+ address_equal = super().__eq__(other)
2019
+ if address_equal is NotImplemented:
2020
+ return NotImplemented
2021
+ if not address_equal:
2022
+ return False
2023
+ return self._scope_id == getattr(other, '_scope_id', None)
2024
+
2025
+ def __reduce__(self):
2026
+ return (self.__class__, (str(self),))
2027
+
2028
+ @property
2029
+ def scope_id(self):
2030
+ """Identifier of a particular zone of the address's scope.
2031
+
2032
+ See RFC 4007 for details.
2033
+
2034
+ Returns:
2035
+ A string identifying the zone of the address if specified, else None.
2036
+
2037
+ """
2038
+ return self._scope_id
2039
+
2040
+ @property
2041
+ def packed(self):
2042
+ """The binary representation of this address."""
2043
+ return v6_int_to_packed(self._ip)
2044
+
2045
+ @property
2046
+ def is_multicast(self):
2047
+ """Test if the address is reserved for multicast use.
2048
+
2049
+ Returns:
2050
+ A boolean, True if the address is a multicast address.
2051
+ See RFC 2373 2.7 for details.
2052
+
2053
+ """
2054
+ ipv4_mapped = self.ipv4_mapped
2055
+ if ipv4_mapped is not None:
2056
+ return ipv4_mapped.is_multicast
2057
+ return self in self._constants._multicast_network
2058
+
2059
+ @property
2060
+ def is_reserved(self):
2061
+ """Test if the address is otherwise IETF reserved.
2062
+
2063
+ Returns:
2064
+ A boolean, True if the address is within one of the
2065
+ reserved IPv6 Network ranges.
2066
+
2067
+ """
2068
+ ipv4_mapped = self.ipv4_mapped
2069
+ if ipv4_mapped is not None:
2070
+ return ipv4_mapped.is_reserved
2071
+ return any(self in x for x in self._constants._reserved_networks)
2072
+
2073
+ @property
2074
+ def is_link_local(self):
2075
+ """Test if the address is reserved for link-local.
2076
+
2077
+ Returns:
2078
+ A boolean, True if the address is reserved per RFC 4291.
2079
+
2080
+ """
2081
+ ipv4_mapped = self.ipv4_mapped
2082
+ if ipv4_mapped is not None:
2083
+ return ipv4_mapped.is_link_local
2084
+ return self in self._constants._linklocal_network
2085
+
2086
+ @property
2087
+ def is_site_local(self):
2088
+ """Test if the address is reserved for site-local.
2089
+
2090
+ Note that the site-local address space has been deprecated by RFC 3879.
2091
+ Use is_private to test if this address is in the space of unique local
2092
+ addresses as defined by RFC 4193.
2093
+
2094
+ Returns:
2095
+ A boolean, True if the address is reserved per RFC 3513 2.5.6.
2096
+
2097
+ """
2098
+ return self in self._constants._sitelocal_network
2099
+
2100
+ @property
2101
+ @functools.lru_cache()
2102
+ def is_private(self):
2103
+ """``True`` if the address is defined as not globally reachable by
2104
+ iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_
2105
+ (for IPv6) with the following exceptions:
2106
+
2107
+ * ``is_private`` is ``False`` for ``100.64.0.0/10``
2108
+ * For IPv4-mapped IPv6-addresses the ``is_private`` value is determined by the
2109
+ semantics of the underlying IPv4 addresses and the following condition holds
2110
+ (see :attr:`IPv6Address.ipv4_mapped`)::
2111
+
2112
+ address.is_private == address.ipv4_mapped.is_private
2113
+
2114
+ ``is_private`` has value opposite to :attr:`is_global`, except for the ``100.64.0.0/10``
2115
+ IPv4 range where they are both ``False``.
2116
+ """
2117
+ ipv4_mapped = self.ipv4_mapped
2118
+ if ipv4_mapped is not None:
2119
+ return ipv4_mapped.is_private
2120
+ return (
2121
+ any(self in net for net in self._constants._private_networks)
2122
+ and all(self not in net for net in self._constants._private_networks_exceptions)
2123
+ )
2124
+
2125
+ @property
2126
+ def is_global(self):
2127
+ """``True`` if the address is defined as globally reachable by
2128
+ iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_
2129
+ (for IPv6) with the following exception:
2130
+
2131
+ For IPv4-mapped IPv6-addresses the ``is_private`` value is determined by the
2132
+ semantics of the underlying IPv4 addresses and the following condition holds
2133
+ (see :attr:`IPv6Address.ipv4_mapped`)::
2134
+
2135
+ address.is_global == address.ipv4_mapped.is_global
2136
+
2137
+ ``is_global`` has value opposite to :attr:`is_private`, except for the ``100.64.0.0/10``
2138
+ IPv4 range where they are both ``False``.
2139
+ """
2140
+ ipv4_mapped = self.ipv4_mapped
2141
+ if ipv4_mapped is not None:
2142
+ return ipv4_mapped.is_global
2143
+ return not self.is_private
2144
+
2145
+ @property
2146
+ def is_unspecified(self):
2147
+ """Test if the address is unspecified.
2148
+
2149
+ Returns:
2150
+ A boolean, True if this is the unspecified address as defined in
2151
+ RFC 2373 2.5.2.
2152
+
2153
+ """
2154
+ ipv4_mapped = self.ipv4_mapped
2155
+ if ipv4_mapped is not None:
2156
+ return ipv4_mapped.is_unspecified
2157
+ return self._ip == 0
2158
+
2159
+ @property
2160
+ def is_loopback(self):
2161
+ """Test if the address is a loopback address.
2162
+
2163
+ Returns:
2164
+ A boolean, True if the address is a loopback address as defined in
2165
+ RFC 2373 2.5.3.
2166
+
2167
+ """
2168
+ ipv4_mapped = self.ipv4_mapped
2169
+ if ipv4_mapped is not None:
2170
+ return ipv4_mapped.is_loopback
2171
+ return self._ip == 1
2172
+
2173
+ @property
2174
+ def ipv4_mapped(self):
2175
+ """Return the IPv4 mapped address.
2176
+
2177
+ Returns:
2178
+ If the IPv6 address is a v4 mapped address, return the
2179
+ IPv4 mapped address. Return None otherwise.
2180
+
2181
+ """
2182
+ if (self._ip >> 32) != 0xFFFF:
2183
+ return None
2184
+ return IPv4Address(self._ip & 0xFFFFFFFF)
2185
+
2186
+ @property
2187
+ def teredo(self):
2188
+ """Tuple of embedded teredo IPs.
2189
+
2190
+ Returns:
2191
+ Tuple of the (server, client) IPs or None if the address
2192
+ doesn't appear to be a teredo address (doesn't start with
2193
+ 2001::/32)
2194
+
2195
+ """
2196
+ if (self._ip >> 96) != 0x20010000:
2197
+ return None
2198
+ return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
2199
+ IPv4Address(~self._ip & 0xFFFFFFFF))
2200
+
2201
+ @property
2202
+ def sixtofour(self):
2203
+ """Return the IPv4 6to4 embedded address.
2204
+
2205
+ Returns:
2206
+ The IPv4 6to4-embedded address if present or None if the
2207
+ address doesn't appear to contain a 6to4 embedded address.
2208
+
2209
+ """
2210
+ if (self._ip >> 112) != 0x2002:
2211
+ return None
2212
+ return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
2213
+
2214
+
2215
+ class IPv6Interface(IPv6Address):
2216
+
2217
+ def __init__(self, address):
2218
+ addr, mask = self._split_addr_prefix(address)
2219
+
2220
+ IPv6Address.__init__(self, addr)
2221
+ self.network = IPv6Network((addr, mask), strict=False)
2222
+ self.netmask = self.network.netmask
2223
+ self._prefixlen = self.network._prefixlen
2224
+
2225
+ @functools.cached_property
2226
+ def hostmask(self):
2227
+ return self.network.hostmask
2228
+
2229
+ def __str__(self):
2230
+ return '%s/%d' % (super().__str__(),
2231
+ self._prefixlen)
2232
+
2233
+ def __eq__(self, other):
2234
+ address_equal = IPv6Address.__eq__(self, other)
2235
+ if address_equal is NotImplemented or not address_equal:
2236
+ return address_equal
2237
+ try:
2238
+ return self.network == other.network
2239
+ except AttributeError:
2240
+ # An interface with an associated network is NOT the
2241
+ # same as an unassociated address. That's why the hash
2242
+ # takes the extra info into account.
2243
+ return False
2244
+
2245
+ def __lt__(self, other):
2246
+ address_less = IPv6Address.__lt__(self, other)
2247
+ if address_less is NotImplemented:
2248
+ return address_less
2249
+ try:
2250
+ return (self.network < other.network or
2251
+ self.network == other.network and address_less)
2252
+ except AttributeError:
2253
+ # We *do* allow addresses and interfaces to be sorted. The
2254
+ # unassociated address is considered less than all interfaces.
2255
+ return False
2256
+
2257
+ def __hash__(self):
2258
+ return hash((self._ip, self._prefixlen, int(self.network.network_address)))
2259
+
2260
+ __reduce__ = _IPAddressBase.__reduce__
2261
+
2262
+ @property
2263
+ def ip(self):
2264
+ return IPv6Address(self._ip)
2265
+
2266
+ @property
2267
+ def with_prefixlen(self):
2268
+ return '%s/%s' % (self._string_from_ip_int(self._ip),
2269
+ self._prefixlen)
2270
+
2271
+ @property
2272
+ def with_netmask(self):
2273
+ return '%s/%s' % (self._string_from_ip_int(self._ip),
2274
+ self.netmask)
2275
+
2276
+ @property
2277
+ def with_hostmask(self):
2278
+ return '%s/%s' % (self._string_from_ip_int(self._ip),
2279
+ self.hostmask)
2280
+
2281
+ @property
2282
+ def is_unspecified(self):
2283
+ return self._ip == 0 and self.network.is_unspecified
2284
+
2285
+ @property
2286
+ def is_loopback(self):
2287
+ return super().is_loopback and self.network.is_loopback
2288
+
2289
+
2290
+ class IPv6Network(_BaseV6, _BaseNetwork):
2291
+
2292
+ """This class represents and manipulates 128-bit IPv6 networks.
2293
+
2294
+ Attributes: [examples for IPv6('2001:db8::1000/124')]
2295
+ .network_address: IPv6Address('2001:db8::1000')
2296
+ .hostmask: IPv6Address('::f')
2297
+ .broadcast_address: IPv6Address('2001:db8::100f')
2298
+ .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
2299
+ .prefixlen: 124
2300
+
2301
+ """
2302
+
2303
+ # Class to use when creating address objects
2304
+ _address_class = IPv6Address
2305
+
2306
+ def __init__(self, address, strict=True):
2307
+ """Instantiate a new IPv6 Network object.
2308
+
2309
+ Args:
2310
+ address: A string or integer representing the IPv6 network or the
2311
+ IP and prefix/netmask.
2312
+ '2001:db8::/128'
2313
+ '2001:db8:0000:0000:0000:0000:0000:0000/128'
2314
+ '2001:db8::'
2315
+ are all functionally the same in IPv6. That is to say,
2316
+ failing to provide a subnetmask will create an object with
2317
+ a mask of /128.
2318
+
2319
+ Additionally, an integer can be passed, so
2320
+ IPv6Network('2001:db8::') ==
2321
+ IPv6Network(42540766411282592856903984951653826560)
2322
+ or, more generally
2323
+ IPv6Network(int(IPv6Network('2001:db8::'))) ==
2324
+ IPv6Network('2001:db8::')
2325
+
2326
+ strict: A boolean. If true, ensure that we have been passed
2327
+ A true network address, eg, 2001:db8::1000/124 and not an
2328
+ IP address on a network, eg, 2001:db8::1/124.
2329
+
2330
+ Raises:
2331
+ AddressValueError: If address isn't a valid IPv6 address.
2332
+ NetmaskValueError: If the netmask isn't valid for
2333
+ an IPv6 address.
2334
+ ValueError: If strict was True and a network address was not
2335
+ supplied.
2336
+ """
2337
+ addr, mask = self._split_addr_prefix(address)
2338
+
2339
+ self.network_address = IPv6Address(addr)
2340
+ self.netmask, self._prefixlen = self._make_netmask(mask)
2341
+ packed = int(self.network_address)
2342
+ if packed & int(self.netmask) != packed:
2343
+ if strict:
2344
+ raise ValueError('%s has host bits set' % self)
2345
+ else:
2346
+ self.network_address = IPv6Address(packed &
2347
+ int(self.netmask))
2348
+
2349
+ if self._prefixlen == (self._max_prefixlen - 1):
2350
+ self.hosts = self.__iter__
2351
+ elif self._prefixlen == self._max_prefixlen:
2352
+ self.hosts = lambda: [IPv6Address(addr)]
2353
+
2354
+ def hosts(self):
2355
+ """Generate Iterator over usable hosts in a network.
2356
+
2357
+ This is like __iter__ except it doesn't return the
2358
+ Subnet-Router anycast address.
2359
+
2360
+ """
2361
+ network = int(self.network_address)
2362
+ broadcast = int(self.broadcast_address)
2363
+ for x in range(network + 1, broadcast + 1):
2364
+ yield self._address_class(x)
2365
+
2366
+ @property
2367
+ def is_site_local(self):
2368
+ """Test if the address is reserved for site-local.
2369
+
2370
+ Note that the site-local address space has been deprecated by RFC 3879.
2371
+ Use is_private to test if this address is in the space of unique local
2372
+ addresses as defined by RFC 4193.
2373
+
2374
+ Returns:
2375
+ A boolean, True if the address is reserved per RFC 3513 2.5.6.
2376
+
2377
+ """
2378
+ return (self.network_address.is_site_local and
2379
+ self.broadcast_address.is_site_local)
2380
+
2381
+
2382
+ class _IPv6Constants:
2383
+
2384
+ _linklocal_network = IPv6Network('fe80::/10')
2385
+
2386
+ _multicast_network = IPv6Network('ff00::/8')
2387
+
2388
+ # Not globally reachable address blocks listed on
2389
+ # https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
2390
+ _private_networks = [
2391
+ IPv6Network('::1/128'),
2392
+ IPv6Network('::/128'),
2393
+ IPv6Network('::ffff:0:0/96'),
2394
+ IPv6Network('64:ff9b:1::/48'),
2395
+ IPv6Network('100::/64'),
2396
+ IPv6Network('2001::/23'),
2397
+ IPv6Network('2001:db8::/32'),
2398
+ # IANA says N/A, let's consider it not globally reachable to be safe
2399
+ IPv6Network('2002::/16'),
2400
+ # RFC 9637: https://www.rfc-editor.org/rfc/rfc9637.html#section-6-2.2
2401
+ IPv6Network('3fff::/20'),
2402
+ IPv6Network('fc00::/7'),
2403
+ IPv6Network('fe80::/10'),
2404
+ ]
2405
+
2406
+ _private_networks_exceptions = [
2407
+ IPv6Network('2001:1::1/128'),
2408
+ IPv6Network('2001:1::2/128'),
2409
+ IPv6Network('2001:3::/32'),
2410
+ IPv6Network('2001:4:112::/48'),
2411
+ IPv6Network('2001:20::/28'),
2412
+ IPv6Network('2001:30::/28'),
2413
+ ]
2414
+
2415
+ _reserved_networks = [
2416
+ IPv6Network('::/8'), IPv6Network('100::/8'),
2417
+ IPv6Network('200::/7'), IPv6Network('400::/6'),
2418
+ IPv6Network('800::/5'), IPv6Network('1000::/4'),
2419
+ IPv6Network('4000::/3'), IPv6Network('6000::/3'),
2420
+ IPv6Network('8000::/3'), IPv6Network('A000::/3'),
2421
+ IPv6Network('C000::/3'), IPv6Network('E000::/4'),
2422
+ IPv6Network('F000::/5'), IPv6Network('F800::/6'),
2423
+ IPv6Network('FE00::/9'),
2424
+ ]
2425
+
2426
+ _sitelocal_network = IPv6Network('fec0::/10')
2427
+
2428
+
2429
+ IPv6Address._constants = _IPv6Constants
2430
+ IPv6Network._constants = _IPv6Constants
physworld_p1_20261018/envs/p1/lib/python3.11/json/__init__.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""JSON (JavaScript Object Notation) <https://json.org> is a subset of
2
+ JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
3
+ interchange format.
4
+
5
+ :mod:`json` exposes an API familiar to users of the standard library
6
+ :mod:`marshal` and :mod:`pickle` modules. It is derived from a
7
+ version of the externally maintained simplejson library.
8
+
9
+ Encoding basic Python object hierarchies::
10
+
11
+ >>> import json
12
+ >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
13
+ '["foo", {"bar": ["baz", null, 1.0, 2]}]'
14
+ >>> print(json.dumps("\"foo\bar"))
15
+ "\"foo\bar"
16
+ >>> print(json.dumps('\u1234'))
17
+ "\u1234"
18
+ >>> print(json.dumps('\\'))
19
+ "\\"
20
+ >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
21
+ {"a": 0, "b": 0, "c": 0}
22
+ >>> from io import StringIO
23
+ >>> io = StringIO()
24
+ >>> json.dump(['streaming API'], io)
25
+ >>> io.getvalue()
26
+ '["streaming API"]'
27
+
28
+ Compact encoding::
29
+
30
+ >>> import json
31
+ >>> mydict = {'4': 5, '6': 7}
32
+ >>> json.dumps([1,2,3,mydict], separators=(',', ':'))
33
+ '[1,2,3,{"4":5,"6":7}]'
34
+
35
+ Pretty printing::
36
+
37
+ >>> import json
38
+ >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
39
+ {
40
+ "4": 5,
41
+ "6": 7
42
+ }
43
+
44
+ Decoding JSON::
45
+
46
+ >>> import json
47
+ >>> obj = ['foo', {'bar': ['baz', None, 1.0, 2]}]
48
+ >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
49
+ True
50
+ >>> json.loads('"\\"foo\\bar"') == '"foo\x08ar'
51
+ True
52
+ >>> from io import StringIO
53
+ >>> io = StringIO('["streaming API"]')
54
+ >>> json.load(io)[0] == 'streaming API'
55
+ True
56
+
57
+ Specializing JSON object decoding::
58
+
59
+ >>> import json
60
+ >>> def as_complex(dct):
61
+ ... if '__complex__' in dct:
62
+ ... return complex(dct['real'], dct['imag'])
63
+ ... return dct
64
+ ...
65
+ >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
66
+ ... object_hook=as_complex)
67
+ (1+2j)
68
+ >>> from decimal import Decimal
69
+ >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1')
70
+ True
71
+
72
+ Specializing JSON object encoding::
73
+
74
+ >>> import json
75
+ >>> def encode_complex(obj):
76
+ ... if isinstance(obj, complex):
77
+ ... return [obj.real, obj.imag]
78
+ ... raise TypeError(f'Object of type {obj.__class__.__name__} '
79
+ ... f'is not JSON serializable')
80
+ ...
81
+ >>> json.dumps(2 + 1j, default=encode_complex)
82
+ '[2.0, 1.0]'
83
+ >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
84
+ '[2.0, 1.0]'
85
+ >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
86
+ '[2.0, 1.0]'
87
+
88
+
89
+ Using json.tool from the shell to validate and pretty-print::
90
+
91
+ $ echo '{"json":"obj"}' | python -m json.tool
92
+ {
93
+ "json": "obj"
94
+ }
95
+ $ echo '{ 1.2:3.4}' | python -m json.tool
96
+ Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
97
+ """
98
+ __version__ = '2.0.9'
99
+ __all__ = [
100
+ 'dump', 'dumps', 'load', 'loads',
101
+ 'JSONDecoder', 'JSONDecodeError', 'JSONEncoder',
102
+ ]
103
+
104
+ __author__ = 'Bob Ippolito <bob@redivi.com>'
105
+
106
+ from .decoder import JSONDecoder, JSONDecodeError
107
+ from .encoder import JSONEncoder
108
+ import codecs
109
+
110
+ _default_encoder = JSONEncoder(
111
+ skipkeys=False,
112
+ ensure_ascii=True,
113
+ check_circular=True,
114
+ allow_nan=True,
115
+ indent=None,
116
+ separators=None,
117
+ default=None,
118
+ )
119
+
120
+ def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,
121
+ allow_nan=True, cls=None, indent=None, separators=None,
122
+ default=None, sort_keys=False, **kw):
123
+ """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
124
+ ``.write()``-supporting file-like object).
125
+
126
+ If ``skipkeys`` is true then ``dict`` keys that are not basic types
127
+ (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
128
+ instead of raising a ``TypeError``.
129
+
130
+ If ``ensure_ascii`` is false, then the strings written to ``fp`` can
131
+ contain non-ASCII characters if they appear in strings contained in
132
+ ``obj``. Otherwise, all such characters are escaped in JSON strings.
133
+
134
+ If ``check_circular`` is false, then the circular reference check
135
+ for container types will be skipped and a circular reference will
136
+ result in an ``RecursionError`` (or worse).
137
+
138
+ If ``allow_nan`` is false, then it will be a ``ValueError`` to
139
+ serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
140
+ in strict compliance of the JSON specification, instead of using the
141
+ JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
142
+
143
+ If ``indent`` is a non-negative integer, then JSON array elements and
144
+ object members will be pretty-printed with that indent level. An indent
145
+ level of 0 will only insert newlines. ``None`` is the most compact
146
+ representation.
147
+
148
+ If specified, ``separators`` should be an ``(item_separator, key_separator)``
149
+ tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and
150
+ ``(',', ': ')`` otherwise. To get the most compact JSON representation,
151
+ you should specify ``(',', ':')`` to eliminate whitespace.
152
+
153
+ ``default(obj)`` is a function that should return a serializable version
154
+ of obj or raise TypeError. The default simply raises TypeError.
155
+
156
+ If *sort_keys* is true (default: ``False``), then the output of
157
+ dictionaries will be sorted by key.
158
+
159
+ To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
160
+ ``.default()`` method to serialize additional types), specify it with
161
+ the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.
162
+
163
+ """
164
+ # cached encoder
165
+ if (not skipkeys and ensure_ascii and
166
+ check_circular and allow_nan and
167
+ cls is None and indent is None and separators is None and
168
+ default is None and not sort_keys and not kw):
169
+ iterable = _default_encoder.iterencode(obj)
170
+ else:
171
+ if cls is None:
172
+ cls = JSONEncoder
173
+ iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
174
+ check_circular=check_circular, allow_nan=allow_nan, indent=indent,
175
+ separators=separators,
176
+ default=default, sort_keys=sort_keys, **kw).iterencode(obj)
177
+ # could accelerate with writelines in some versions of Python, at
178
+ # a debuggability cost
179
+ for chunk in iterable:
180
+ fp.write(chunk)
181
+
182
+
183
+ def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,
184
+ allow_nan=True, cls=None, indent=None, separators=None,
185
+ default=None, sort_keys=False, **kw):
186
+ """Serialize ``obj`` to a JSON formatted ``str``.
187
+
188
+ If ``skipkeys`` is true then ``dict`` keys that are not basic types
189
+ (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
190
+ instead of raising a ``TypeError``.
191
+
192
+ If ``ensure_ascii`` is false, then the return value can contain non-ASCII
193
+ characters if they appear in strings contained in ``obj``. Otherwise, all
194
+ such characters are escaped in JSON strings.
195
+
196
+ If ``check_circular`` is false, then the circular reference check
197
+ for container types will be skipped and a circular reference will
198
+ result in an ``RecursionError`` (or worse).
199
+
200
+ If ``allow_nan`` is false, then it will be a ``ValueError`` to
201
+ serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
202
+ strict compliance of the JSON specification, instead of using the
203
+ JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
204
+
205
+ If ``indent`` is a non-negative integer, then JSON array elements and
206
+ object members will be pretty-printed with that indent level. An indent
207
+ level of 0 will only insert newlines. ``None`` is the most compact
208
+ representation.
209
+
210
+ If specified, ``separators`` should be an ``(item_separator, key_separator)``
211
+ tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and
212
+ ``(',', ': ')`` otherwise. To get the most compact JSON representation,
213
+ you should specify ``(',', ':')`` to eliminate whitespace.
214
+
215
+ ``default(obj)`` is a function that should return a serializable version
216
+ of obj or raise TypeError. The default simply raises TypeError.
217
+
218
+ If *sort_keys* is true (default: ``False``), then the output of
219
+ dictionaries will be sorted by key.
220
+
221
+ To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
222
+ ``.default()`` method to serialize additional types), specify it with
223
+ the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.
224
+
225
+ """
226
+ # cached encoder
227
+ if (not skipkeys and ensure_ascii and
228
+ check_circular and allow_nan and
229
+ cls is None and indent is None and separators is None and
230
+ default is None and not sort_keys and not kw):
231
+ return _default_encoder.encode(obj)
232
+ if cls is None:
233
+ cls = JSONEncoder
234
+ return cls(
235
+ skipkeys=skipkeys, ensure_ascii=ensure_ascii,
236
+ check_circular=check_circular, allow_nan=allow_nan, indent=indent,
237
+ separators=separators, default=default, sort_keys=sort_keys,
238
+ **kw).encode(obj)
239
+
240
+
241
+ _default_decoder = JSONDecoder(object_hook=None, object_pairs_hook=None)
242
+
243
+
244
+ def detect_encoding(b):
245
+ bstartswith = b.startswith
246
+ if bstartswith((codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE)):
247
+ return 'utf-32'
248
+ if bstartswith((codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE)):
249
+ return 'utf-16'
250
+ if bstartswith(codecs.BOM_UTF8):
251
+ return 'utf-8-sig'
252
+
253
+ if len(b) >= 4:
254
+ if not b[0]:
255
+ # 00 00 -- -- - utf-32-be
256
+ # 00 XX -- -- - utf-16-be
257
+ return 'utf-16-be' if b[1] else 'utf-32-be'
258
+ if not b[1]:
259
+ # XX 00 00 00 - utf-32-le
260
+ # XX 00 00 XX - utf-16-le
261
+ # XX 00 XX -- - utf-16-le
262
+ return 'utf-16-le' if b[2] or b[3] else 'utf-32-le'
263
+ elif len(b) == 2:
264
+ if not b[0]:
265
+ # 00 XX - utf-16-be
266
+ return 'utf-16-be'
267
+ if not b[1]:
268
+ # XX 00 - utf-16-le
269
+ return 'utf-16-le'
270
+ # default
271
+ return 'utf-8'
272
+
273
+
274
+ def load(fp, *, cls=None, object_hook=None, parse_float=None,
275
+ parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
276
+ """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
277
+ a JSON document) to a Python object.
278
+
279
+ ``object_hook`` is an optional function that will be called with the
280
+ result of any object literal decode (a ``dict``). The return value of
281
+ ``object_hook`` will be used instead of the ``dict``. This feature
282
+ can be used to implement custom decoders (e.g. JSON-RPC class hinting).
283
+
284
+ ``object_pairs_hook`` is an optional function that will be called with the
285
+ result of any object literal decoded with an ordered list of pairs. The
286
+ return value of ``object_pairs_hook`` will be used instead of the ``dict``.
287
+ This feature can be used to implement custom decoders. If ``object_hook``
288
+ is also defined, the ``object_pairs_hook`` takes priority.
289
+
290
+ To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
291
+ kwarg; otherwise ``JSONDecoder`` is used.
292
+ """
293
+ return loads(fp.read(),
294
+ cls=cls, object_hook=object_hook,
295
+ parse_float=parse_float, parse_int=parse_int,
296
+ parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
297
+
298
+
299
+ def loads(s, *, cls=None, object_hook=None, parse_float=None,
300
+ parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
301
+ """Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
302
+ containing a JSON document) to a Python object.
303
+
304
+ ``object_hook`` is an optional function that will be called with the
305
+ result of any object literal decode (a ``dict``). The return value of
306
+ ``object_hook`` will be used instead of the ``dict``. This feature
307
+ can be used to implement custom decoders (e.g. JSON-RPC class hinting).
308
+
309
+ ``object_pairs_hook`` is an optional function that will be called with the
310
+ result of any object literal decoded with an ordered list of pairs. The
311
+ return value of ``object_pairs_hook`` will be used instead of the ``dict``.
312
+ This feature can be used to implement custom decoders. If ``object_hook``
313
+ is also defined, the ``object_pairs_hook`` takes priority.
314
+
315
+ ``parse_float``, if specified, will be called with the string
316
+ of every JSON float to be decoded. By default this is equivalent to
317
+ float(num_str). This can be used to use another datatype or parser
318
+ for JSON floats (e.g. decimal.Decimal).
319
+
320
+ ``parse_int``, if specified, will be called with the string
321
+ of every JSON int to be decoded. By default this is equivalent to
322
+ int(num_str). This can be used to use another datatype or parser
323
+ for JSON integers (e.g. float).
324
+
325
+ ``parse_constant``, if specified, will be called with one of the
326
+ following strings: -Infinity, Infinity, NaN.
327
+ This can be used to raise an exception if invalid JSON numbers
328
+ are encountered.
329
+
330
+ To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
331
+ kwarg; otherwise ``JSONDecoder`` is used.
332
+ """
333
+ if isinstance(s, str):
334
+ if s.startswith('\ufeff'):
335
+ raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
336
+ s, 0)
337
+ else:
338
+ if not isinstance(s, (bytes, bytearray)):
339
+ raise TypeError(f'the JSON object must be str, bytes or bytearray, '
340
+ f'not {s.__class__.__name__}')
341
+ s = s.decode(detect_encoding(s), 'surrogatepass')
342
+
343
+ if (cls is None and object_hook is None and
344
+ parse_int is None and parse_float is None and
345
+ parse_constant is None and object_pairs_hook is None and not kw):
346
+ return _default_decoder.decode(s)
347
+ if cls is None:
348
+ cls = JSONDecoder
349
+ if object_hook is not None:
350
+ kw['object_hook'] = object_hook
351
+ if object_pairs_hook is not None:
352
+ kw['object_pairs_hook'] = object_pairs_hook
353
+ if parse_float is not None:
354
+ kw['parse_float'] = parse_float
355
+ if parse_int is not None:
356
+ kw['parse_int'] = parse_int
357
+ if parse_constant is not None:
358
+ kw['parse_constant'] = parse_constant
359
+ return cls(**kw).decode(s)
physworld_p1_20261018/envs/p1/lib/python3.11/json/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (14.5 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/json/__pycache__/decoder.cpython-311.pyc ADDED
Binary file (15.4 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/json/__pycache__/encoder.cpython-311.pyc ADDED
Binary file (17.1 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/json/__pycache__/scanner.cpython-311.pyc ADDED
Binary file (3.9 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/json/__pycache__/tool.cpython-311.pyc ADDED
Binary file (5 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/json/decoder.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of JSONDecoder
2
+ """
3
+ import re
4
+
5
+ from json import scanner
6
+ try:
7
+ from _json import scanstring as c_scanstring
8
+ except ImportError:
9
+ c_scanstring = None
10
+
11
+ __all__ = ['JSONDecoder', 'JSONDecodeError']
12
+
13
+ FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
14
+
15
+ NaN = float('nan')
16
+ PosInf = float('inf')
17
+ NegInf = float('-inf')
18
+
19
+
20
+ class JSONDecodeError(ValueError):
21
+ """Subclass of ValueError with the following additional properties:
22
+
23
+ msg: The unformatted error message
24
+ doc: The JSON document being parsed
25
+ pos: The start index of doc where parsing failed
26
+ lineno: The line corresponding to pos
27
+ colno: The column corresponding to pos
28
+
29
+ """
30
+ # Note that this exception is used from _json
31
+ def __init__(self, msg, doc, pos):
32
+ lineno = doc.count('\n', 0, pos) + 1
33
+ colno = pos - doc.rfind('\n', 0, pos)
34
+ errmsg = '%s: line %d column %d (char %d)' % (msg, lineno, colno, pos)
35
+ ValueError.__init__(self, errmsg)
36
+ self.msg = msg
37
+ self.doc = doc
38
+ self.pos = pos
39
+ self.lineno = lineno
40
+ self.colno = colno
41
+
42
+ def __reduce__(self):
43
+ return self.__class__, (self.msg, self.doc, self.pos)
44
+
45
+
46
+ _CONSTANTS = {
47
+ '-Infinity': NegInf,
48
+ 'Infinity': PosInf,
49
+ 'NaN': NaN,
50
+ }
51
+
52
+
53
+ STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS)
54
+ BACKSLASH = {
55
+ '"': '"', '\\': '\\', '/': '/',
56
+ 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t',
57
+ }
58
+
59
+ def _decode_uXXXX(s, pos):
60
+ esc = s[pos + 1:pos + 5]
61
+ if len(esc) == 4 and esc[1] not in 'xX':
62
+ try:
63
+ return int(esc, 16)
64
+ except ValueError:
65
+ pass
66
+ msg = "Invalid \\uXXXX escape"
67
+ raise JSONDecodeError(msg, s, pos)
68
+
69
+ def py_scanstring(s, end, strict=True,
70
+ _b=BACKSLASH, _m=STRINGCHUNK.match):
71
+ """Scan the string s for a JSON string. End is the index of the
72
+ character in s after the quote that started the JSON string.
73
+ Unescapes all valid JSON string escape sequences and raises ValueError
74
+ on attempt to decode an invalid string. If strict is False then literal
75
+ control characters are allowed in the string.
76
+
77
+ Returns a tuple of the decoded string and the index of the character in s
78
+ after the end quote."""
79
+ chunks = []
80
+ _append = chunks.append
81
+ begin = end - 1
82
+ while 1:
83
+ chunk = _m(s, end)
84
+ if chunk is None:
85
+ raise JSONDecodeError("Unterminated string starting at", s, begin)
86
+ end = chunk.end()
87
+ content, terminator = chunk.groups()
88
+ # Content is contains zero or more unescaped string characters
89
+ if content:
90
+ _append(content)
91
+ # Terminator is the end of string, a literal control character,
92
+ # or a backslash denoting that an escape sequence follows
93
+ if terminator == '"':
94
+ break
95
+ elif terminator != '\\':
96
+ if strict:
97
+ #msg = "Invalid control character %r at" % (terminator,)
98
+ msg = "Invalid control character {0!r} at".format(terminator)
99
+ raise JSONDecodeError(msg, s, end)
100
+ else:
101
+ _append(terminator)
102
+ continue
103
+ try:
104
+ esc = s[end]
105
+ except IndexError:
106
+ raise JSONDecodeError("Unterminated string starting at",
107
+ s, begin) from None
108
+ # If not a unicode escape sequence, must be in the lookup table
109
+ if esc != 'u':
110
+ try:
111
+ char = _b[esc]
112
+ except KeyError:
113
+ msg = "Invalid \\escape: {0!r}".format(esc)
114
+ raise JSONDecodeError(msg, s, end)
115
+ end += 1
116
+ else:
117
+ uni = _decode_uXXXX(s, end)
118
+ end += 5
119
+ if 0xd800 <= uni <= 0xdbff and s[end:end + 2] == '\\u':
120
+ uni2 = _decode_uXXXX(s, end + 1)
121
+ if 0xdc00 <= uni2 <= 0xdfff:
122
+ uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00))
123
+ end += 6
124
+ char = chr(uni)
125
+ _append(char)
126
+ return ''.join(chunks), end
127
+
128
+
129
+ # Use speedup if available
130
+ scanstring = c_scanstring or py_scanstring
131
+
132
+ WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS)
133
+ WHITESPACE_STR = ' \t\n\r'
134
+
135
+
136
+ def JSONObject(s_and_end, strict, scan_once, object_hook, object_pairs_hook,
137
+ memo=None, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
138
+ s, end = s_and_end
139
+ pairs = []
140
+ pairs_append = pairs.append
141
+ # Backwards compatibility
142
+ if memo is None:
143
+ memo = {}
144
+ memo_get = memo.setdefault
145
+ # Use a slice to prevent IndexError from being raised, the following
146
+ # check will raise a more specific ValueError if the string is empty
147
+ nextchar = s[end:end + 1]
148
+ # Normally we expect nextchar == '"'
149
+ if nextchar != '"':
150
+ if nextchar in _ws:
151
+ end = _w(s, end).end()
152
+ nextchar = s[end:end + 1]
153
+ # Trivial empty object
154
+ if nextchar == '}':
155
+ if object_pairs_hook is not None:
156
+ result = object_pairs_hook(pairs)
157
+ return result, end + 1
158
+ pairs = {}
159
+ if object_hook is not None:
160
+ pairs = object_hook(pairs)
161
+ return pairs, end + 1
162
+ elif nextchar != '"':
163
+ raise JSONDecodeError(
164
+ "Expecting property name enclosed in double quotes", s, end)
165
+ end += 1
166
+ while True:
167
+ key, end = scanstring(s, end, strict)
168
+ key = memo_get(key, key)
169
+ # To skip some function call overhead we optimize the fast paths where
170
+ # the JSON key separator is ": " or just ":".
171
+ if s[end:end + 1] != ':':
172
+ end = _w(s, end).end()
173
+ if s[end:end + 1] != ':':
174
+ raise JSONDecodeError("Expecting ':' delimiter", s, end)
175
+ end += 1
176
+
177
+ try:
178
+ if s[end] in _ws:
179
+ end += 1
180
+ if s[end] in _ws:
181
+ end = _w(s, end + 1).end()
182
+ except IndexError:
183
+ pass
184
+
185
+ try:
186
+ value, end = scan_once(s, end)
187
+ except StopIteration as err:
188
+ raise JSONDecodeError("Expecting value", s, err.value) from None
189
+ pairs_append((key, value))
190
+ try:
191
+ nextchar = s[end]
192
+ if nextchar in _ws:
193
+ end = _w(s, end + 1).end()
194
+ nextchar = s[end]
195
+ except IndexError:
196
+ nextchar = ''
197
+ end += 1
198
+
199
+ if nextchar == '}':
200
+ break
201
+ elif nextchar != ',':
202
+ raise JSONDecodeError("Expecting ',' delimiter", s, end - 1)
203
+ end = _w(s, end).end()
204
+ nextchar = s[end:end + 1]
205
+ end += 1
206
+ if nextchar != '"':
207
+ raise JSONDecodeError(
208
+ "Expecting property name enclosed in double quotes", s, end - 1)
209
+ if object_pairs_hook is not None:
210
+ result = object_pairs_hook(pairs)
211
+ return result, end
212
+ pairs = dict(pairs)
213
+ if object_hook is not None:
214
+ pairs = object_hook(pairs)
215
+ return pairs, end
216
+
217
+ def JSONArray(s_and_end, scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
218
+ s, end = s_and_end
219
+ values = []
220
+ nextchar = s[end:end + 1]
221
+ if nextchar in _ws:
222
+ end = _w(s, end + 1).end()
223
+ nextchar = s[end:end + 1]
224
+ # Look-ahead for trivial empty array
225
+ if nextchar == ']':
226
+ return values, end + 1
227
+ _append = values.append
228
+ while True:
229
+ try:
230
+ value, end = scan_once(s, end)
231
+ except StopIteration as err:
232
+ raise JSONDecodeError("Expecting value", s, err.value) from None
233
+ _append(value)
234
+ nextchar = s[end:end + 1]
235
+ if nextchar in _ws:
236
+ end = _w(s, end + 1).end()
237
+ nextchar = s[end:end + 1]
238
+ end += 1
239
+ if nextchar == ']':
240
+ break
241
+ elif nextchar != ',':
242
+ raise JSONDecodeError("Expecting ',' delimiter", s, end - 1)
243
+ try:
244
+ if s[end] in _ws:
245
+ end += 1
246
+ if s[end] in _ws:
247
+ end = _w(s, end + 1).end()
248
+ except IndexError:
249
+ pass
250
+
251
+ return values, end
252
+
253
+
254
+ class JSONDecoder(object):
255
+ """Simple JSON <https://json.org> decoder
256
+
257
+ Performs the following translations in decoding by default:
258
+
259
+ +---------------+-------------------+
260
+ | JSON | Python |
261
+ +===============+===================+
262
+ | object | dict |
263
+ +---------------+-------------------+
264
+ | array | list |
265
+ +---------------+-------------------+
266
+ | string | str |
267
+ +---------------+-------------------+
268
+ | number (int) | int |
269
+ +---------------+-------------------+
270
+ | number (real) | float |
271
+ +---------------+-------------------+
272
+ | true | True |
273
+ +---------------+-------------------+
274
+ | false | False |
275
+ +---------------+-------------------+
276
+ | null | None |
277
+ +---------------+-------------------+
278
+
279
+ It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
280
+ their corresponding ``float`` values, which is outside the JSON spec.
281
+
282
+ """
283
+
284
+ def __init__(self, *, object_hook=None, parse_float=None,
285
+ parse_int=None, parse_constant=None, strict=True,
286
+ object_pairs_hook=None):
287
+ """``object_hook``, if specified, will be called with the result
288
+ of every JSON object decoded and its return value will be used in
289
+ place of the given ``dict``. This can be used to provide custom
290
+ deserializations (e.g. to support JSON-RPC class hinting).
291
+
292
+ ``object_pairs_hook``, if specified will be called with the result of
293
+ every JSON object decoded with an ordered list of pairs. The return
294
+ value of ``object_pairs_hook`` will be used instead of the ``dict``.
295
+ This feature can be used to implement custom decoders.
296
+ If ``object_hook`` is also defined, the ``object_pairs_hook`` takes
297
+ priority.
298
+
299
+ ``parse_float``, if specified, will be called with the string
300
+ of every JSON float to be decoded. By default this is equivalent to
301
+ float(num_str). This can be used to use another datatype or parser
302
+ for JSON floats (e.g. decimal.Decimal).
303
+
304
+ ``parse_int``, if specified, will be called with the string
305
+ of every JSON int to be decoded. By default this is equivalent to
306
+ int(num_str). This can be used to use another datatype or parser
307
+ for JSON integers (e.g. float).
308
+
309
+ ``parse_constant``, if specified, will be called with one of the
310
+ following strings: -Infinity, Infinity, NaN.
311
+ This can be used to raise an exception if invalid JSON numbers
312
+ are encountered.
313
+
314
+ If ``strict`` is false (true is the default), then control
315
+ characters will be allowed inside strings. Control characters in
316
+ this context are those with character codes in the 0-31 range,
317
+ including ``'\\t'`` (tab), ``'\\n'``, ``'\\r'`` and ``'\\0'``.
318
+ """
319
+ self.object_hook = object_hook
320
+ self.parse_float = parse_float or float
321
+ self.parse_int = parse_int or int
322
+ self.parse_constant = parse_constant or _CONSTANTS.__getitem__
323
+ self.strict = strict
324
+ self.object_pairs_hook = object_pairs_hook
325
+ self.parse_object = JSONObject
326
+ self.parse_array = JSONArray
327
+ self.parse_string = scanstring
328
+ self.memo = {}
329
+ self.scan_once = scanner.make_scanner(self)
330
+
331
+
332
+ def decode(self, s, _w=WHITESPACE.match):
333
+ """Return the Python representation of ``s`` (a ``str`` instance
334
+ containing a JSON document).
335
+
336
+ """
337
+ obj, end = self.raw_decode(s, idx=_w(s, 0).end())
338
+ end = _w(s, end).end()
339
+ if end != len(s):
340
+ raise JSONDecodeError("Extra data", s, end)
341
+ return obj
342
+
343
+ def raw_decode(self, s, idx=0):
344
+ """Decode a JSON document from ``s`` (a ``str`` beginning with
345
+ a JSON document) and return a 2-tuple of the Python
346
+ representation and the index in ``s`` where the document ended.
347
+
348
+ This can be used to decode a JSON document from a string that may
349
+ have extraneous data at the end.
350
+
351
+ """
352
+ try:
353
+ obj, end = self.scan_once(s, idx)
354
+ except StopIteration as err:
355
+ raise JSONDecodeError("Expecting value", s, err.value) from None
356
+ return obj, end
physworld_p1_20261018/envs/p1/lib/python3.11/json/encoder.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of JSONEncoder
2
+ """
3
+ import re
4
+
5
+ try:
6
+ from _json import encode_basestring_ascii as c_encode_basestring_ascii
7
+ except ImportError:
8
+ c_encode_basestring_ascii = None
9
+ try:
10
+ from _json import encode_basestring as c_encode_basestring
11
+ except ImportError:
12
+ c_encode_basestring = None
13
+ try:
14
+ from _json import make_encoder as c_make_encoder
15
+ except ImportError:
16
+ c_make_encoder = None
17
+
18
+ ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
19
+ ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
20
+ HAS_UTF8 = re.compile(b'[\x80-\xff]')
21
+ ESCAPE_DCT = {
22
+ '\\': '\\\\',
23
+ '"': '\\"',
24
+ '\b': '\\b',
25
+ '\f': '\\f',
26
+ '\n': '\\n',
27
+ '\r': '\\r',
28
+ '\t': '\\t',
29
+ }
30
+ for i in range(0x20):
31
+ ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
32
+ #ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
33
+ del i
34
+
35
+ INFINITY = float('inf')
36
+
37
+ def py_encode_basestring(s):
38
+ """Return a JSON representation of a Python string
39
+
40
+ """
41
+ def replace(match):
42
+ return ESCAPE_DCT[match.group(0)]
43
+ return '"' + ESCAPE.sub(replace, s) + '"'
44
+
45
+
46
+ encode_basestring = (c_encode_basestring or py_encode_basestring)
47
+
48
+
49
+ def py_encode_basestring_ascii(s):
50
+ """Return an ASCII-only JSON representation of a Python string
51
+
52
+ """
53
+ def replace(match):
54
+ s = match.group(0)
55
+ try:
56
+ return ESCAPE_DCT[s]
57
+ except KeyError:
58
+ n = ord(s)
59
+ if n < 0x10000:
60
+ return '\\u{0:04x}'.format(n)
61
+ #return '\\u%04x' % (n,)
62
+ else:
63
+ # surrogate pair
64
+ n -= 0x10000
65
+ s1 = 0xd800 | ((n >> 10) & 0x3ff)
66
+ s2 = 0xdc00 | (n & 0x3ff)
67
+ return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
68
+ return '"' + ESCAPE_ASCII.sub(replace, s) + '"'
69
+
70
+
71
+ encode_basestring_ascii = (
72
+ c_encode_basestring_ascii or py_encode_basestring_ascii)
73
+
74
+ class JSONEncoder(object):
75
+ """Extensible JSON <https://json.org> encoder for Python data structures.
76
+
77
+ Supports the following objects and types by default:
78
+
79
+ +-------------------+---------------+
80
+ | Python | JSON |
81
+ +===================+===============+
82
+ | dict | object |
83
+ +-------------------+---------------+
84
+ | list, tuple | array |
85
+ +-------------------+---------------+
86
+ | str | string |
87
+ +-------------------+---------------+
88
+ | int, float | number |
89
+ +-------------------+---------------+
90
+ | True | true |
91
+ +-------------------+---------------+
92
+ | False | false |
93
+ +-------------------+---------------+
94
+ | None | null |
95
+ +-------------------+---------------+
96
+
97
+ To extend this to recognize other objects, subclass and implement a
98
+ ``.default()`` method with another method that returns a serializable
99
+ object for ``o`` if possible, otherwise it should call the superclass
100
+ implementation (to raise ``TypeError``).
101
+
102
+ """
103
+ item_separator = ', '
104
+ key_separator = ': '
105
+ def __init__(self, *, skipkeys=False, ensure_ascii=True,
106
+ check_circular=True, allow_nan=True, sort_keys=False,
107
+ indent=None, separators=None, default=None):
108
+ """Constructor for JSONEncoder, with sensible defaults.
109
+
110
+ If skipkeys is false, then it is a TypeError to attempt
111
+ encoding of keys that are not str, int, float or None. If
112
+ skipkeys is True, such items are simply skipped.
113
+
114
+ If ensure_ascii is true, the output is guaranteed to be str
115
+ objects with all incoming non-ASCII characters escaped. If
116
+ ensure_ascii is false, the output can contain non-ASCII characters.
117
+
118
+ If check_circular is true, then lists, dicts, and custom encoded
119
+ objects will be checked for circular references during encoding to
120
+ prevent an infinite recursion (which would cause an RecursionError).
121
+ Otherwise, no such check takes place.
122
+
123
+ If allow_nan is true, then NaN, Infinity, and -Infinity will be
124
+ encoded as such. This behavior is not JSON specification compliant,
125
+ but is consistent with most JavaScript based encoders and decoders.
126
+ Otherwise, it will be a ValueError to encode such floats.
127
+
128
+ If sort_keys is true, then the output of dictionaries will be
129
+ sorted by key; this is useful for regression tests to ensure
130
+ that JSON serializations can be compared on a day-to-day basis.
131
+
132
+ If indent is a non-negative integer, then JSON array
133
+ elements and object members will be pretty-printed with that
134
+ indent level. An indent level of 0 will only insert newlines.
135
+ None is the most compact representation.
136
+
137
+ If specified, separators should be an (item_separator, key_separator)
138
+ tuple. The default is (', ', ': ') if *indent* is ``None`` and
139
+ (',', ': ') otherwise. To get the most compact JSON representation,
140
+ you should specify (',', ':') to eliminate whitespace.
141
+
142
+ If specified, default is a function that gets called for objects
143
+ that can't otherwise be serialized. It should return a JSON encodable
144
+ version of the object or raise a ``TypeError``.
145
+
146
+ """
147
+
148
+ self.skipkeys = skipkeys
149
+ self.ensure_ascii = ensure_ascii
150
+ self.check_circular = check_circular
151
+ self.allow_nan = allow_nan
152
+ self.sort_keys = sort_keys
153
+ self.indent = indent
154
+ if separators is not None:
155
+ self.item_separator, self.key_separator = separators
156
+ elif indent is not None:
157
+ self.item_separator = ','
158
+ if default is not None:
159
+ self.default = default
160
+
161
+ def default(self, o):
162
+ """Implement this method in a subclass such that it returns
163
+ a serializable object for ``o``, or calls the base implementation
164
+ (to raise a ``TypeError``).
165
+
166
+ For example, to support arbitrary iterators, you could
167
+ implement default like this::
168
+
169
+ def default(self, o):
170
+ try:
171
+ iterable = iter(o)
172
+ except TypeError:
173
+ pass
174
+ else:
175
+ return list(iterable)
176
+ # Let the base class default method raise the TypeError
177
+ return super().default(o)
178
+
179
+ """
180
+ raise TypeError(f'Object of type {o.__class__.__name__} '
181
+ f'is not JSON serializable')
182
+
183
+ def encode(self, o):
184
+ """Return a JSON string representation of a Python data structure.
185
+
186
+ >>> from json.encoder import JSONEncoder
187
+ >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
188
+ '{"foo": ["bar", "baz"]}'
189
+
190
+ """
191
+ # This is for extremely simple cases and benchmarks.
192
+ if isinstance(o, str):
193
+ if self.ensure_ascii:
194
+ return encode_basestring_ascii(o)
195
+ else:
196
+ return encode_basestring(o)
197
+ # This doesn't pass the iterator directly to ''.join() because the
198
+ # exceptions aren't as detailed. The list call should be roughly
199
+ # equivalent to the PySequence_Fast that ''.join() would do.
200
+ chunks = self.iterencode(o, _one_shot=True)
201
+ if not isinstance(chunks, (list, tuple)):
202
+ chunks = list(chunks)
203
+ return ''.join(chunks)
204
+
205
+ def iterencode(self, o, _one_shot=False):
206
+ """Encode the given object and yield each string
207
+ representation as available.
208
+
209
+ For example::
210
+
211
+ for chunk in JSONEncoder().iterencode(bigobject):
212
+ mysocket.write(chunk)
213
+
214
+ """
215
+ if self.check_circular:
216
+ markers = {}
217
+ else:
218
+ markers = None
219
+ if self.ensure_ascii:
220
+ _encoder = encode_basestring_ascii
221
+ else:
222
+ _encoder = encode_basestring
223
+
224
+ def floatstr(o, allow_nan=self.allow_nan,
225
+ _repr=float.__repr__, _inf=INFINITY, _neginf=-INFINITY):
226
+ # Check for specials. Note that this type of test is processor
227
+ # and/or platform-specific, so do tests which don't depend on the
228
+ # internals.
229
+
230
+ if o != o:
231
+ text = 'NaN'
232
+ elif o == _inf:
233
+ text = 'Infinity'
234
+ elif o == _neginf:
235
+ text = '-Infinity'
236
+ else:
237
+ return _repr(o)
238
+
239
+ if not allow_nan:
240
+ raise ValueError(
241
+ "Out of range float values are not JSON compliant: " +
242
+ repr(o))
243
+
244
+ return text
245
+
246
+
247
+ if (_one_shot and c_make_encoder is not None
248
+ and self.indent is None):
249
+ _iterencode = c_make_encoder(
250
+ markers, self.default, _encoder, self.indent,
251
+ self.key_separator, self.item_separator, self.sort_keys,
252
+ self.skipkeys, self.allow_nan)
253
+ else:
254
+ _iterencode = _make_iterencode(
255
+ markers, self.default, _encoder, self.indent, floatstr,
256
+ self.key_separator, self.item_separator, self.sort_keys,
257
+ self.skipkeys, _one_shot)
258
+ return _iterencode(o, 0)
259
+
260
+ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
261
+ _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
262
+ ## HACK: hand-optimized bytecode; turn globals into locals
263
+ ValueError=ValueError,
264
+ dict=dict,
265
+ float=float,
266
+ id=id,
267
+ int=int,
268
+ isinstance=isinstance,
269
+ list=list,
270
+ str=str,
271
+ tuple=tuple,
272
+ _intstr=int.__repr__,
273
+ ):
274
+
275
+ if _indent is not None and not isinstance(_indent, str):
276
+ _indent = ' ' * _indent
277
+
278
+ def _iterencode_list(lst, _current_indent_level):
279
+ if not lst:
280
+ yield '[]'
281
+ return
282
+ if markers is not None:
283
+ markerid = id(lst)
284
+ if markerid in markers:
285
+ raise ValueError("Circular reference detected")
286
+ markers[markerid] = lst
287
+ buf = '['
288
+ if _indent is not None:
289
+ _current_indent_level += 1
290
+ newline_indent = '\n' + _indent * _current_indent_level
291
+ separator = _item_separator + newline_indent
292
+ buf += newline_indent
293
+ else:
294
+ newline_indent = None
295
+ separator = _item_separator
296
+ first = True
297
+ for value in lst:
298
+ if first:
299
+ first = False
300
+ else:
301
+ buf = separator
302
+ if isinstance(value, str):
303
+ yield buf + _encoder(value)
304
+ elif value is None:
305
+ yield buf + 'null'
306
+ elif value is True:
307
+ yield buf + 'true'
308
+ elif value is False:
309
+ yield buf + 'false'
310
+ elif isinstance(value, int):
311
+ # Subclasses of int/float may override __repr__, but we still
312
+ # want to encode them as integers/floats in JSON. One example
313
+ # within the standard library is IntEnum.
314
+ yield buf + _intstr(value)
315
+ elif isinstance(value, float):
316
+ # see comment above for int
317
+ yield buf + _floatstr(value)
318
+ else:
319
+ yield buf
320
+ if isinstance(value, (list, tuple)):
321
+ chunks = _iterencode_list(value, _current_indent_level)
322
+ elif isinstance(value, dict):
323
+ chunks = _iterencode_dict(value, _current_indent_level)
324
+ else:
325
+ chunks = _iterencode(value, _current_indent_level)
326
+ yield from chunks
327
+ if newline_indent is not None:
328
+ _current_indent_level -= 1
329
+ yield '\n' + _indent * _current_indent_level
330
+ yield ']'
331
+ if markers is not None:
332
+ del markers[markerid]
333
+
334
+ def _iterencode_dict(dct, _current_indent_level):
335
+ if not dct:
336
+ yield '{}'
337
+ return
338
+ if markers is not None:
339
+ markerid = id(dct)
340
+ if markerid in markers:
341
+ raise ValueError("Circular reference detected")
342
+ markers[markerid] = dct
343
+ yield '{'
344
+ if _indent is not None:
345
+ _current_indent_level += 1
346
+ newline_indent = '\n' + _indent * _current_indent_level
347
+ item_separator = _item_separator + newline_indent
348
+ yield newline_indent
349
+ else:
350
+ newline_indent = None
351
+ item_separator = _item_separator
352
+ first = True
353
+ if _sort_keys:
354
+ items = sorted(dct.items())
355
+ else:
356
+ items = dct.items()
357
+ for key, value in items:
358
+ if isinstance(key, str):
359
+ pass
360
+ # JavaScript is weakly typed for these, so it makes sense to
361
+ # also allow them. Many encoders seem to do something like this.
362
+ elif isinstance(key, float):
363
+ # see comment for int/float in _make_iterencode
364
+ key = _floatstr(key)
365
+ elif key is True:
366
+ key = 'true'
367
+ elif key is False:
368
+ key = 'false'
369
+ elif key is None:
370
+ key = 'null'
371
+ elif isinstance(key, int):
372
+ # see comment for int/float in _make_iterencode
373
+ key = _intstr(key)
374
+ elif _skipkeys:
375
+ continue
376
+ else:
377
+ raise TypeError(f'keys must be str, int, float, bool or None, '
378
+ f'not {key.__class__.__name__}')
379
+ if first:
380
+ first = False
381
+ else:
382
+ yield item_separator
383
+ yield _encoder(key)
384
+ yield _key_separator
385
+ if isinstance(value, str):
386
+ yield _encoder(value)
387
+ elif value is None:
388
+ yield 'null'
389
+ elif value is True:
390
+ yield 'true'
391
+ elif value is False:
392
+ yield 'false'
393
+ elif isinstance(value, int):
394
+ # see comment for int/float in _make_iterencode
395
+ yield _intstr(value)
396
+ elif isinstance(value, float):
397
+ # see comment for int/float in _make_iterencode
398
+ yield _floatstr(value)
399
+ else:
400
+ if isinstance(value, (list, tuple)):
401
+ chunks = _iterencode_list(value, _current_indent_level)
402
+ elif isinstance(value, dict):
403
+ chunks = _iterencode_dict(value, _current_indent_level)
404
+ else:
405
+ chunks = _iterencode(value, _current_indent_level)
406
+ yield from chunks
407
+ if newline_indent is not None:
408
+ _current_indent_level -= 1
409
+ yield '\n' + _indent * _current_indent_level
410
+ yield '}'
411
+ if markers is not None:
412
+ del markers[markerid]
413
+
414
+ def _iterencode(o, _current_indent_level):
415
+ if isinstance(o, str):
416
+ yield _encoder(o)
417
+ elif o is None:
418
+ yield 'null'
419
+ elif o is True:
420
+ yield 'true'
421
+ elif o is False:
422
+ yield 'false'
423
+ elif isinstance(o, int):
424
+ # see comment for int/float in _make_iterencode
425
+ yield _intstr(o)
426
+ elif isinstance(o, float):
427
+ # see comment for int/float in _make_iterencode
428
+ yield _floatstr(o)
429
+ elif isinstance(o, (list, tuple)):
430
+ yield from _iterencode_list(o, _current_indent_level)
431
+ elif isinstance(o, dict):
432
+ yield from _iterencode_dict(o, _current_indent_level)
433
+ else:
434
+ if markers is not None:
435
+ markerid = id(o)
436
+ if markerid in markers:
437
+ raise ValueError("Circular reference detected")
438
+ markers[markerid] = o
439
+ o = _default(o)
440
+ yield from _iterencode(o, _current_indent_level)
441
+ if markers is not None:
442
+ del markers[markerid]
443
+ return _iterencode
physworld_p1_20261018/envs/p1/lib/python3.11/json/scanner.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """JSON token scanner
2
+ """
3
+ import re
4
+ try:
5
+ from _json import make_scanner as c_make_scanner
6
+ except ImportError:
7
+ c_make_scanner = None
8
+
9
+ __all__ = ['make_scanner']
10
+
11
+ NUMBER_RE = re.compile(
12
+ r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?',
13
+ (re.VERBOSE | re.MULTILINE | re.DOTALL))
14
+
15
+ def py_make_scanner(context):
16
+ parse_object = context.parse_object
17
+ parse_array = context.parse_array
18
+ parse_string = context.parse_string
19
+ match_number = NUMBER_RE.match
20
+ strict = context.strict
21
+ parse_float = context.parse_float
22
+ parse_int = context.parse_int
23
+ parse_constant = context.parse_constant
24
+ object_hook = context.object_hook
25
+ object_pairs_hook = context.object_pairs_hook
26
+ memo = context.memo
27
+
28
+ def _scan_once(string, idx):
29
+ try:
30
+ nextchar = string[idx]
31
+ except IndexError:
32
+ raise StopIteration(idx) from None
33
+
34
+ if nextchar == '"':
35
+ return parse_string(string, idx + 1, strict)
36
+ elif nextchar == '{':
37
+ return parse_object((string, idx + 1), strict,
38
+ _scan_once, object_hook, object_pairs_hook, memo)
39
+ elif nextchar == '[':
40
+ return parse_array((string, idx + 1), _scan_once)
41
+ elif nextchar == 'n' and string[idx:idx + 4] == 'null':
42
+ return None, idx + 4
43
+ elif nextchar == 't' and string[idx:idx + 4] == 'true':
44
+ return True, idx + 4
45
+ elif nextchar == 'f' and string[idx:idx + 5] == 'false':
46
+ return False, idx + 5
47
+
48
+ m = match_number(string, idx)
49
+ if m is not None:
50
+ integer, frac, exp = m.groups()
51
+ if frac or exp:
52
+ res = parse_float(integer + (frac or '') + (exp or ''))
53
+ else:
54
+ res = parse_int(integer)
55
+ return res, m.end()
56
+ elif nextchar == 'N' and string[idx:idx + 3] == 'NaN':
57
+ return parse_constant('NaN'), idx + 3
58
+ elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity':
59
+ return parse_constant('Infinity'), idx + 8
60
+ elif nextchar == '-' and string[idx:idx + 9] == '-Infinity':
61
+ return parse_constant('-Infinity'), idx + 9
62
+ else:
63
+ raise StopIteration(idx)
64
+
65
+ def scan_once(string, idx):
66
+ try:
67
+ return _scan_once(string, idx)
68
+ finally:
69
+ memo.clear()
70
+
71
+ return scan_once
72
+
73
+ make_scanner = c_make_scanner or py_make_scanner
physworld_p1_20261018/envs/p1/lib/python3.11/json/tool.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""Command-line tool to validate and pretty-print JSON
2
+
3
+ Usage::
4
+
5
+ $ echo '{"json":"obj"}' | python -m json.tool
6
+ {
7
+ "json": "obj"
8
+ }
9
+ $ echo '{ 1.2:3.4}' | python -m json.tool
10
+ Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
11
+
12
+ """
13
+ import argparse
14
+ import json
15
+ import sys
16
+ from pathlib import Path
17
+
18
+
19
+ def main():
20
+ prog = 'python -m json.tool'
21
+ description = ('A simple command line interface for json module '
22
+ 'to validate and pretty-print JSON objects.')
23
+ parser = argparse.ArgumentParser(prog=prog, description=description)
24
+ parser.add_argument('infile', nargs='?',
25
+ type=argparse.FileType(encoding="utf-8"),
26
+ help='a JSON file to be validated or pretty-printed',
27
+ default=sys.stdin)
28
+ parser.add_argument('outfile', nargs='?',
29
+ type=Path,
30
+ help='write the output of infile to outfile',
31
+ default=None)
32
+ parser.add_argument('--sort-keys', action='store_true', default=False,
33
+ help='sort the output of dictionaries alphabetically by key')
34
+ parser.add_argument('--no-ensure-ascii', dest='ensure_ascii', action='store_false',
35
+ help='disable escaping of non-ASCII characters')
36
+ parser.add_argument('--json-lines', action='store_true', default=False,
37
+ help='parse input using the JSON Lines format. '
38
+ 'Use with --no-indent or --compact to produce valid JSON Lines output.')
39
+ group = parser.add_mutually_exclusive_group()
40
+ group.add_argument('--indent', default=4, type=int,
41
+ help='separate items with newlines and use this number '
42
+ 'of spaces for indentation')
43
+ group.add_argument('--tab', action='store_const', dest='indent',
44
+ const='\t', help='separate items with newlines and use '
45
+ 'tabs for indentation')
46
+ group.add_argument('--no-indent', action='store_const', dest='indent',
47
+ const=None,
48
+ help='separate items with spaces rather than newlines')
49
+ group.add_argument('--compact', action='store_true',
50
+ help='suppress all whitespace separation (most compact)')
51
+ options = parser.parse_args()
52
+
53
+ dump_args = {
54
+ 'sort_keys': options.sort_keys,
55
+ 'indent': options.indent,
56
+ 'ensure_ascii': options.ensure_ascii,
57
+ }
58
+ if options.compact:
59
+ dump_args['indent'] = None
60
+ dump_args['separators'] = ',', ':'
61
+
62
+ with options.infile as infile:
63
+ try:
64
+ if options.json_lines:
65
+ objs = (json.loads(line) for line in infile)
66
+ else:
67
+ objs = (json.load(infile),)
68
+
69
+ if options.outfile is None:
70
+ out = sys.stdout
71
+ else:
72
+ out = options.outfile.open('w', encoding='utf-8')
73
+ with out as outfile:
74
+ for obj in objs:
75
+ json.dump(obj, outfile, **dump_args)
76
+ outfile.write('\n')
77
+ except ValueError as e:
78
+ raise SystemExit(e)
79
+
80
+
81
+ if __name__ == '__main__':
82
+ try:
83
+ main()
84
+ except BrokenPipeError as exc:
85
+ sys.exit(exc.errno)
physworld_p1_20261018/envs/p1/lib/python3.11/keyword.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Keywords (from "Grammar/python.gram")
2
+
3
+ This file is automatically generated; please don't muck it up!
4
+
5
+ To update the symbols in this file, 'cd' to the top directory of
6
+ the python source tree and run:
7
+
8
+ PYTHONPATH=Tools/peg_generator python3 -m pegen.keywordgen \
9
+ Grammar/python.gram \
10
+ Grammar/Tokens \
11
+ Lib/keyword.py
12
+
13
+ Alternatively, you can run 'make regen-keyword'.
14
+ """
15
+
16
+ __all__ = ["iskeyword", "issoftkeyword", "kwlist", "softkwlist"]
17
+
18
+ kwlist = [
19
+ 'False',
20
+ 'None',
21
+ 'True',
22
+ 'and',
23
+ 'as',
24
+ 'assert',
25
+ 'async',
26
+ 'await',
27
+ 'break',
28
+ 'class',
29
+ 'continue',
30
+ 'def',
31
+ 'del',
32
+ 'elif',
33
+ 'else',
34
+ 'except',
35
+ 'finally',
36
+ 'for',
37
+ 'from',
38
+ 'global',
39
+ 'if',
40
+ 'import',
41
+ 'in',
42
+ 'is',
43
+ 'lambda',
44
+ 'nonlocal',
45
+ 'not',
46
+ 'or',
47
+ 'pass',
48
+ 'raise',
49
+ 'return',
50
+ 'try',
51
+ 'while',
52
+ 'with',
53
+ 'yield'
54
+ ]
55
+
56
+ softkwlist = [
57
+ '_',
58
+ 'case',
59
+ 'match'
60
+ ]
61
+
62
+ iskeyword = frozenset(kwlist).__contains__
63
+ issoftkeyword = frozenset(softkwlist).__contains__
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_asyncio.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef5a59071f1a60950da91c16fcc8419b82dcbf4196d48dd39e4e97a7cced8183
3
+ size 267032
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_bisect.cpython-311-x86_64-linux-gnu.so ADDED
Binary file (62.5 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_blake2.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33ba75983e6dd60c95b310f7e88f7265da5f11595484911fe94e90f4044f1627
3
+ size 220016
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_bz2.cpython-311-x86_64-linux-gnu.so ADDED
Binary file (94.5 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_codecs_cn.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4168e703afa42010d2ae2f3319eaff40fe14521b1f9b98ce8035dc8a2a4e9fee
3
+ size 189096
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_codecs_hk.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b06314ad18de2cd60a26752b524ad4e4b6d8f219d4a6218bfab67b629e6da38b
3
+ size 188552
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_codecs_iso2022.cpython-311-x86_64-linux-gnu.so ADDED
Binary file (75 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_codecs_jp.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:182df9c648d47113dd9d9d89718f0bfa06c86e3863966308c64e4359c3f2a687
3
+ size 319904
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_codecs_kr.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a7b94562dbaa66f085ec45cb927f9727b531dbfe9002742ac865cbb09f610f1
3
+ size 174240
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_codecs_tw.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:85f54d372abef23628cc1573ebd4475bbe191d170e75c765c5a3c205e327b307
3
+ size 137696
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_contextvars.cpython-311-x86_64-linux-gnu.so ADDED
Binary file (26.9 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_crypt.cpython-311-x86_64-linux-gnu.so ADDED
Binary file (29.8 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_csv.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:78364103c40b8535ed2cbe17de8b8dbdc3d1a2b038c2e6d310465736dec58910
3
+ size 142648
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_ctypes.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:21732cc4c11d2a4fc8bff76af727ad37739fb09263823df0c96bc695fcfeef4b
3
+ size 608328
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_ctypes_test.cpython-311-x86_64-linux-gnu.so ADDED
Binary file (80.1 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_curses.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2fbce259bd36d2f01194006e1663de5d42acd8959a064102d591a59b5d757163
3
+ size 523976
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_curses_panel.cpython-311-x86_64-linux-gnu.so ADDED
Binary file (78.8 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_datetime.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dfb6a0dd9d767a6b1b1cb92099cd87251a80d26aeb505e628009305d4b43e69f
3
+ size 636760
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_decimal.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:79875f61e106655119f772869552f66c1d6d1d68c20b3fba56f751bbd5d8832a
3
+ size 1531136
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_elementtree.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:144e127c3ba46c6af99f0a3e1f69b7e800366e1a4058f228f7da64db81430ef1
3
+ size 346016
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_hashlib.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f9997af3e88175e787c5e2d5605b661ee8673a2e465f856ac76c0c558a63286
3
+ size 206984
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_heapq.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c81178bab4e773fd65628e437765c6109517188af969cea35a2f34cfb88f5cf3
3
+ size 115080
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_json.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a23fafa02b7237785e5fae2161b477f0bf92c041899e1a53dbefb64c76146ac
3
+ size 233832
physworld_p1_20261018/envs/p1/lib/python3.11/lib-dynload/_lsprof.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b50785efc44c999e744e791995a3328ffc69cddd9f24eb67589d16abdd81a031
3
+ size 135088