Debian Codegraph @

Doc/library/uuid.rst

raw
1 :mod:`!uuid` --- UUID objects according to :rfc:`9562`
2 ======================================================
3
4 .. module:: uuid
5 :synopsis: UUID objects (universally unique identifiers) according to RFC 9562
6 .. moduleauthor:: Ka-Ping Yee <[email protected]>
7 .. sectionauthor:: George Yoshida <[email protected]>
8
9 **Source code:** :source:`Lib/uuid.py`
10
11 --------------
12
13 This module provides immutable :class:`UUID` objects (the :class:`UUID` class)
14 and :ref:`functions <uuid-factory-functions>` for generating UUIDs corresponding
15 to a specific UUID version as specified in :rfc:`9562` (which supersedes :rfc:`4122`),
16 for example, :func:`uuid1` for UUID version 1, :func:`uuid3` for UUID version 3, and so on.
17 Note that UUID version 2 is deliberately omitted as it is outside the scope of the RFC.
18
19 If all you want is a unique ID, you should probably call :func:`uuid1` or
20 :func:`uuid4`. Note that :func:`uuid1` may compromise privacy since it creates
21 a UUID containing the computer's network address. :func:`uuid4` creates a
22 random UUID.
23
24 Depending on support from the underlying platform, :func:`uuid1` may or may
25 not return a "safe" UUID. A safe UUID is one which is generated using
26 synchronization methods that ensure no two processes can obtain the same
27 UUID. All instances of :class:`UUID` have an :attr:`~UUID.is_safe` attribute
28 which relays any information about the UUID's safety, using this enumeration:
29
30 .. class:: SafeUUID
31
32 .. versionadded:: 3.7
33
34 .. attribute:: SafeUUID.safe
35
36 The UUID was generated by the platform in a multiprocessing-safe way.
37
38 .. attribute:: SafeUUID.unsafe
39
40 The UUID was not generated in a multiprocessing-safe way.
41
42 .. attribute:: SafeUUID.unknown
43
44 The platform does not provide information on whether the UUID was
45 generated safely or not.
46
47 .. class:: UUID(hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None, *, is_safe=SafeUUID.unknown)
48
49 Create a UUID from either a string of 32 hexadecimal digits, a string of 16
50 bytes in big-endian order as the *bytes* argument, a string of 16 bytes in
51 little-endian order as the *bytes_le* argument, a tuple of six integers
52 (32-bit *time_low*, 16-bit *time_mid*, 16-bit *time_hi_version*,
53 8-bit *clock_seq_hi_variant*, 8-bit *clock_seq_low*, 48-bit *node*) as the
54 *fields* argument, or a single 128-bit integer as the *int* argument.
55 When a string of hex digits is given, curly braces, hyphens,
56 and a URN prefix are all optional. For example, these
57 expressions all yield the same UUID::
58
59 UUID('{12345678-1234-5678-1234-567812345678}')
60 UUID('12345678123456781234567812345678')
61 UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
62 UUID(bytes=b'\x12\x34\x56\x78'*4)
63 UUID(bytes_le=b'\x78\x56\x34\x12\x34\x12\x78\x56' +
64 b'\x12\x34\x56\x78\x12\x34\x56\x78')
65 UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
66 UUID(int=0x12345678123456781234567812345678)
67
68 Exactly one of *hex*, *bytes*, *bytes_le*, *fields*, or *int* must be given.
69 The *version* argument is optional; if given, the resulting UUID will have its
70 variant and version number set according to :rfc:`9562`, overriding bits in the
71 given *hex*, *bytes*, *bytes_le*, *fields*, or *int*.
72
73 Comparison of UUID objects are made by way of comparing their
74 :attr:`UUID.int` attributes. Comparison with a non-UUID object
75 raises a :exc:`TypeError`.
76
77 ``str(uuid)`` returns a string in the form
78 ``12345678-1234-5678-1234-567812345678`` where the 32 hexadecimal digits
79 represent the UUID.
80
81 :class:`UUID` instances have these read-only attributes:
82
83 .. attribute:: UUID.bytes
84
85 The UUID as a 16-byte string (containing the six integer fields in big-endian
86 byte order).
87
88
89 .. attribute:: UUID.bytes_le
90
91 The UUID as a 16-byte string (with *time_low*, *time_mid*, and *time_hi_version*
92 in little-endian byte order).
93
94
95 .. attribute:: UUID.fields
96
97 A tuple of the six integer fields of the UUID, which are also available as six
98 individual attributes and two derived attributes:
99
100 .. list-table::
101
102 * - Field
103 - Meaning
104
105 * - .. attribute:: UUID.time_low
106 - The first 32 bits of the UUID. Only relevant to version 1.
107
108 * - .. attribute:: UUID.time_mid
109 - The next 16 bits of the UUID. Only relevant to version 1.
110
111 * - .. attribute:: UUID.time_hi_version
112 - The next 16 bits of the UUID. Only relevant to version 1.
113
114 * - .. attribute:: UUID.clock_seq_hi_variant
115 - The next 8 bits of the UUID. Only relevant to versions 1 and 6.
116
117 * - .. attribute:: UUID.clock_seq_low
118 - The next 8 bits of the UUID. Only relevant to versions 1 and 6.
119
120 * - .. attribute:: UUID.node
121 - The last 48 bits of the UUID. Only relevant to version 1.
122
123 * - .. attribute:: UUID.time
124 - The 60-bit timestamp as a count of 100-nanosecond intervals since
125 Gregorian epoch (1582-10-15 00:00:00) for versions 1 and 6, or the
126 48-bit timestamp in milliseconds since Unix epoch (1970-01-01 00:00:00)
127 for version 7.
128
129 * - .. attribute:: UUID.clock_seq
130 - The 14-bit sequence number. Only relevant to versions 1 and 6.
131
132
133 .. attribute:: UUID.hex
134
135 The UUID as a 32-character lowercase hexadecimal string.
136
137
138 .. attribute:: UUID.int
139
140 The UUID as a 128-bit integer.
141
142
143 .. attribute:: UUID.urn
144
145 The UUID as a URN as specified in :rfc:`9562`.
146
147
148 .. attribute:: UUID.variant
149
150 The UUID variant, which determines the internal layout of the UUID. This will be
151 one of the constants :const:`RESERVED_NCS`, :const:`RFC_4122`,
152 :const:`RESERVED_MICROSOFT`, or :const:`RESERVED_FUTURE`.
153
154
155 .. attribute:: UUID.version
156
157 The UUID version number (1 through 8, meaningful only when the variant is
158 :const:`RFC_4122`).
159
160 .. versionchanged:: 3.14
161 Added UUID versions 6, 7 and 8.
162
163
164 .. attribute:: UUID.is_safe
165
166 An enumeration of :class:`SafeUUID` which indicates whether the platform
167 generated the UUID in a multiprocessing-safe way.
168
169 .. versionadded:: 3.7
170
171 The :mod:`!uuid` module defines the following functions:
172
173
174 .. function:: getnode()
175
176 Get the hardware address as a 48-bit positive integer. The first time this
177 runs, it may launch a separate program, which could be quite slow. If all
178 attempts to obtain the hardware address fail, we choose a random 48-bit
179 number with the multicast bit (least significant bit of the first octet)
180 set to 1 as recommended in :rfc:`4122`. "Hardware address" means the MAC
181 address of a network interface. On a machine with multiple network
182 interfaces, universally administered MAC addresses (i.e. where the second
183 least significant bit of the first octet is *unset*) will be preferred over
184 locally administered MAC addresses, but with no other ordering guarantees.
185
186 .. versionchanged:: 3.7
187 Universally administered MAC addresses are preferred over locally
188 administered MAC addresses, since the former are guaranteed to be
189 globally unique, while the latter are not.
190
191
192 .. _uuid-factory-functions:
193
194 .. function:: uuid1(node=None, clock_seq=None)
195
196 Generate a UUID from a host ID, sequence number, and the current time
197 according to :rfc:`RFC 9562, §5.1 <9562#section-5.1>`.
198
199 When *node* is not specified, :func:`getnode` is used to obtain the hardware
200 address as a 48-bit positive integer. When a sequence number *clock_seq* is
201 not specified, a pseudo-random 14-bit positive integer is generated.
202
203 If *node* or *clock_seq* exceed their expected bit count,
204 only their least significant bits are kept.
205
206
207 .. function:: uuid3(namespace, name)
208
209 Generate a UUID based on the MD5 hash of a namespace identifier (which is a
210 UUID) and a name (which is a :class:`bytes` object or a string
211 that will be encoded using UTF-8)
212 according to :rfc:`RFC 9562, §5.3 <9562#section-5.3>`.
213
214
215 .. function:: uuid4()
216
217 Generate a random UUID in a cryptographically-secure method
218 according to :rfc:`RFC 9562, §5.4 <9562#section-5.4>`.
219
220
221 .. function:: uuid5(namespace, name)
222
223 Generate a UUID based on the SHA-1 hash of a namespace identifier (which is a
224 UUID) and a name (which is a :class:`bytes` object or a string
225 that will be encoded using UTF-8)
226 according to :rfc:`RFC 9562, §5.5 <9562#section-5.5>`.
227
228
229 .. function:: uuid6(node=None, clock_seq=None)
230
231 Generate a UUID from a sequence number and the current time according to
232 :rfc:`RFC 9562, §5.6 <9562#section-5.6>`.
233
234 This is an alternative to :func:`uuid1` to improve database locality.
235
236 When *node* is not specified, :func:`getnode` is used to obtain the hardware
237 address as a 48-bit positive integer. When a sequence number *clock_seq* is
238 not specified, a pseudo-random 14-bit positive integer is generated.
239
240 If *node* or *clock_seq* exceed their expected bit count,
241 only their least significant bits are kept.
242
243 .. versionadded:: 3.14
244
245
246 .. function:: uuid7()
247
248 Generate a time-based UUID according to
249 :rfc:`RFC 9562, §5.7 <9562#section-5.7>`.
250
251 For portability across platforms lacking sub-millisecond precision, UUIDs
252 produced by this function embed a 48-bit timestamp and use a 42-bit counter
253 to guarantee monotonicity within a millisecond.
254
255 .. versionadded:: 3.14
256
257
258 .. function:: uuid8(a=None, b=None, c=None)
259
260 Generate a pseudo-random UUID according to
261 :rfc:`RFC 9562, §5.8 <9562#section-5.8>`.
262
263 When specified, the parameters *a*, *b* and *c* are expected to be
264 positive integers of 48, 12 and 62 bits respectively. If they exceed
265 their expected bit count, only their least significant bits are kept;
266 non-specified arguments are substituted for a pseudo-random integer of
267 appropriate size.
268
269 By default, *a*, *b* and *c* are not generated by a cryptographically
270 secure pseudo-random number generator (CSPRNG). Use :func:`uuid4` when
271 a UUID needs to be used in a security-sensitive context.
272
273 .. versionadded:: 3.14
274
275
276 The :mod:`!uuid` module defines the following namespace identifiers for use with
277 :func:`uuid3` or :func:`uuid5`.
278
279
280 .. data:: NAMESPACE_DNS
281
282 When this namespace is specified, the *name* string is a fully qualified domain
283 name.
284
285
286 .. data:: NAMESPACE_URL
287
288 When this namespace is specified, the *name* string is a URL.
289
290
291 .. data:: NAMESPACE_OID
292
293 When this namespace is specified, the *name* string is an ISO OID.
294
295
296 .. data:: NAMESPACE_X500
297
298 When this namespace is specified, the *name* string is an X.500 DN in DER or a
299 text output format.
300
301 The :mod:`!uuid` module defines the following constants for the possible values
302 of the :attr:`~UUID.variant` attribute:
303
304
305 .. data:: RESERVED_NCS
306
307 Reserved for NCS compatibility.
308
309
310 .. data:: RFC_4122
311
312 Specifies the UUID layout given in :rfc:`4122`. This constant is kept
313 for backward compatibility even though :rfc:`4122` has been superseded
314 by :rfc:`9562`.
315
316
317 .. data:: RESERVED_MICROSOFT
318
319 Reserved for Microsoft compatibility.
320
321
322 .. data:: RESERVED_FUTURE
323
324 Reserved for future definition.
325
326
327 The :mod:`!uuid` module defines the special Nil and Max UUID values:
328
329
330 .. data:: NIL
331
332 A special form of UUID that is specified to have all 128 bits set to zero
333 according to :rfc:`RFC 9562, §5.9 <9562#section-5.9>`.
334
335 .. versionadded:: 3.14
336
337
338 .. data:: MAX
339
340 A special form of UUID that is specified to have all 128 bits set to one
341 according to :rfc:`RFC 9562, §5.10 <9562#section-5.10>`.
342
343 .. versionadded:: 3.14
344
345
346 .. seealso::
347
348 :rfc:`9562` - A Universally Unique IDentifier (UUID) URN Namespace
349 This specification defines a Uniform Resource Name namespace for UUIDs, the
350 internal format of UUIDs, and methods of generating UUIDs.
351
352
353 .. _uuid-cli:
354
355 Command-Line Usage
356 ------------------
357
358 .. versionadded:: 3.12
359
360 The :mod:`!uuid` module can be executed as a script from the command line.
361
362 .. code-block:: sh
363
364 python -m uuid [-h] [-u {uuid1,uuid3,uuid4,uuid5,uuid6,uuid7,uuid8}] [-n NAMESPACE] [-N NAME]
365
366 The following options are accepted:
367
368 .. program:: uuid
369
370 .. option:: -h, --help
371
372 Show the help message and exit.
373
374 .. option:: -u <uuid>
375 --uuid <uuid>
376
377 Specify the function name to use to generate the uuid. By default :func:`uuid4`
378 is used.
379
380 .. versionchanged:: 3.14
381 Allow generating UUID versions 6, 7 and 8.
382
383 .. option:: -n <namespace>
384 --namespace <namespace>
385
386 The namespace is a ``UUID``, or ``@ns`` where ``ns`` is a well-known predefined UUID
387 addressed by namespace name. Such as ``@dns``, ``@url``, ``@oid``, and ``@x500``.
388 Only required for :func:`uuid3` / :func:`uuid5` functions.
389
390 .. option:: -N <name>
391 --name <name>
392
393 The name used as part of generating the uuid. Only required for
394 :func:`uuid3` / :func:`uuid5` functions.
395
396 .. option:: -C <num>
397 --count <num>
398
399 Generate *num* fresh UUIDs.
400
401 .. versionadded:: 3.14
402
403
404 .. _uuid-example:
405
406 Example
407 -------
408
409 Here are some examples of typical usage of the :mod:`!uuid` module::
410
411 >>> import uuid
412
413 >>> # make a UUID based on the host ID and current time
414 >>> uuid.uuid1() # doctest: +SKIP
415 UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
416
417 >>> # make a UUID using an MD5 hash of a namespace UUID and a name
418 >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
419 UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
420
421 >>> # make a random UUID
422 >>> uuid.uuid4()
423 UUID('16fd2706-8baf-433b-82eb-8c7fada847da')
424
425 >>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
426 >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
427 UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
428
429 >>> # make a UUID from a string of hex digits (braces and hyphens ignored)
430 >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')
431
432 >>> # convert a UUID to a string of hex digits in standard form
433 >>> str(x)
434 '00010203-0405-0607-0809-0a0b0c0d0e0f'
435
436 >>> # get the raw 16 bytes of the UUID
437 >>> x.bytes
438 b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
439
440 >>> # make a UUID from a 16-byte string
441 >>> uuid.UUID(bytes=x.bytes)
442 UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
443
444 >>> # get the Nil UUID
445 >>> uuid.NIL
446 UUID('00000000-0000-0000-0000-000000000000')
447
448 >>> # get the Max UUID
449 >>> uuid.MAX
450 UUID('ffffffff-ffff-ffff-ffff-ffffffffffff')
451
452 >>> # same as UUIDv1 but with fields reordered to improve DB locality
453 >>> uuid.uuid6() # doctest: +SKIP
454 UUID('1f0799c0-98b9-62db-92c6-a0d365b91053')
455
456 >>> # get UUIDv7 creation (local) time as a timestamp in milliseconds
457 >>> u = uuid.uuid7()
458 >>> u.time # doctest: +SKIP
459 1743936859822
460
461 >>> # get UUIDv7 creation (local) time as a datetime object
462 >>> import datetime as dt
463 >>> dt.datetime.fromtimestamp(u.time / 1000) # doctest: +SKIP
464 datetime.datetime(...)
465
466 >>> # make a UUID with custom blocks
467 >>> uuid.uuid8(0x12345678, 0x9abcdef0, 0x11223344)
468 UUID('00001234-5678-8ef0-8000-000011223344')
469
470
471 .. _uuid-cli-example:
472
473 Command-Line Example
474 --------------------
475
476 Here are some examples of typical usage of the :mod:`!uuid` command-line interface:
477
478 .. code-block:: shell
479
480 # generate a random UUID - by default uuid4() is used
481 $ python -m uuid
482
483 # generate a UUID using uuid1()
484 $ python -m uuid -u uuid1
485
486 # generate a UUID using uuid5
487 $ python -m uuid -u uuid5 -n @url -N example.com
488
489 # generate 42 random UUIDs
490 $ python -m uuid -C 42