Back to module index

Go to module by name

uuid

UUID objects (universally unique identifiers) according to RFC 4122.

This module provides immutable UUID objects (class UUID) and the functions
uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5
UUIDs as specified in RFC 4122.

If all you want is a unique ID, you should probably call uuid1() or uuid4().
Note that uuid1() may compromise privacy since it creates a UUID containing
the computer's network address.  uuid4() creates a random UUID.

Typical usage:

    >>> import uuid

    # make a UUID based on the host ID and current time
    >>> uuid.uuid1()    # doctest: +SKIP
    UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

    # make a UUID using an MD5 hash of a namespace UUID and a name
    >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
    UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

    # make a random UUID
    >>> uuid.uuid4()    # doctest: +SKIP
    UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

    # make a UUID using a SHA-1 hash of a namespace UUID and a name
    >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
    UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

    # make a UUID from a string of hex digits (braces and hyphens ignored)
    >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')

    # convert a UUID to a string of hex digits in standard form
    >>> str(x)
    '00010203-0405-0607-0809-0a0b0c0d0e0f'

    # get the raw 16 bytes of the UUID
    >>> x.bytes
    b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'

    # make a UUID from a 16-byte string
    >>> uuid.UUID(bytes=x.bytes)
    UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')

Classes

Enum


    Generic enumeration.

    Derive from this class to define new enumerations.
    

SafeUUID

An enumeration.
name = <types.DynamicClassAttribute object at 0x7f75e3bec2e0>
  The name of the Enum member.
safe = <SafeUUID.safe: 0>
unknown = <SafeUUID.unknown: None>
unsafe = <SafeUUID.unsafe: -1>
value = <types.DynamicClassAttribute object at 0x7f75e3bec2b0>
  The value of the Enum member.

UUID

Instances of the UUID class represent UUIDs as specified in RFC 4122.
    UUID objects are immutable, hashable, and usable as dictionary keys.
    Converting a UUID to a string with str() yields something in the form
    '12345678-1234-1234-1234-123456789abc'.  The UUID constructor accepts
    five possible forms: a similar string of hexadecimal digits, or a tuple
    of six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and
    48-bit values respectively) as an argument named 'fields', or a string
    of 16 bytes (with all the integer fields in big-endian order) as an
    argument named 'bytes', or a string of 16 bytes (with the first three
    fields in little-endian order) as an argument named 'bytes_le', or a
    single 128-bit integer as an argument named 'int'.

    UUIDs have these read-only attributes:

        bytes       the UUID as a 16-byte string (containing the six
                    integer fields in big-endian byte order)

        bytes_le    the UUID as a 16-byte string (with time_low, time_mid,
                    and time_hi_version in little-endian byte order)

        fields      a tuple of the six integer fields of the UUID,
                    which are also available as six individual attributes
                    and two derived attributes:

            time_low                the first 32 bits of the UUID
            time_mid                the next 16 bits of the UUID
            time_hi_version         the next 16 bits of the UUID
            clock_seq_hi_variant    the next 8 bits of the UUID
            clock_seq_low           the next 8 bits of the UUID
            node                    the last 48 bits of the UUID

            time                    the 60-bit timestamp
            clock_seq               the 14-bit sequence number

        hex         the UUID as a 32-character hexadecimal string

        int         the UUID as a 128-bit integer

        urn         the UUID as a URN as specified in RFC 4122

        variant     the UUID variant (one of the constants RESERVED_NCS,
                    RFC_4122, RESERVED_MICROSOFT, or RESERVED_FUTURE)

        version     the UUID version number (1 through 5, meaningful only
                    when the variant is RFC_4122)

        is_safe     An enum indicating whether the UUID has been generated in
                    a way that is safe for multiprocessing applications, via
                    uuid_generate_time_safe(3).
    
bytes = <property object at 0x7f75e09ee700>
bytes_le = <property object at 0x7f75e0a81030>
clock_seq = <property object at 0x7f75e0a81620>
clock_seq_hi_variant = <property object at 0x7f75e0a81490>
clock_seq_low = <property object at 0x7f75e0a81580>
fields = <property object at 0x7f75e0a81210>
hex = <property object at 0x7f75e0a816c0>
int = <member 'int' of 'UUID' objects>
is_safe = <member 'is_safe' of 'UUID' objects>
node = <property object at 0x7f75e0a815d0>
time = <property object at 0x7f75e0a81530>
time_hi_version = <property object at 0x7f75e0a82520>
time_low = <property object at 0x7f75e0a812b0>
time_mid = <property object at 0x7f75e0a813a0>
urn = <property object at 0x7f75e0a81760>
variant = <property object at 0x7f75e0a81800>
version = <property object at 0x7f75e0a818f0>

bytes

bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes() -> empty bytes object

Construct an immutable array of bytes from:
  - an iterable yielding integers in range(256)
  - a text string encoded using the specified encoding
  - any object implementing the buffer API.
  - an integer
capitalize(...)

  B.capitalize() -> copy of B

  Return a copy of B with only its first character capitalized (ASCII)
  and the rest lower-cased.
center(self, width, fillchar=b' ', /)

  Return a centered string of length width.

  Padding is done using the specified fill character.
count(...)

  B.count(sub[, start[, end]]) -> int

  Return the number of non-overlapping occurrences of subsection sub in
  bytes B[start:end].  Optional arguments start and end are interpreted
  as in slice notation.
decode(self, /, encoding='utf-8', errors='strict')

  Decode the bytes using the codec registered for encoding.

    encoding
      The encoding with which to decode the bytes.
    errors
      The error handling scheme to use for the handling of decoding errors.
      The default is 'strict' meaning that decoding errors raise a
      UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
      as well as any other name registered with codecs.register_error that
      can handle UnicodeDecodeErrors.
endswith(...)

  B.endswith(suffix[, start[, end]]) -> bool

  Return True if B ends with the specified suffix, False otherwise.
  With optional start, test B beginning at that position.
  With optional end, stop comparing B at that position.
  suffix can also be a tuple of bytes to try.
expandtabs(self, /, tabsize=8)

  Return a copy where all tab characters are expanded using spaces.

  If tabsize is not given, a tab size of 8 characters is assumed.
find(...)

  B.find(sub[, start[, end]]) -> int

  Return the lowest index in B where subsection sub is found,
  such that sub is contained within B[start,end].  Optional
  arguments start and end are interpreted as in slice notation.

  Return -1 on failure.
fromhex(string, /)

  Create a bytes object from a string of hexadecimal numbers.

  Spaces between two numbers are accepted.
  Example: bytes.fromhex('B9 01EF') -> b'\\xb9\\x01\\xef'.
hex(...)

  Create a string of hexadecimal numbers from a bytes object.

    sep
      An optional single character or byte to separate hex bytes.
    bytes_per_sep
      How many bytes between separators.  Positive values count from the
      right, negative values count from the left.

  Example:
  >>> value = b'\xb9\x01\xef'
  >>> value.hex()
  'b901ef'
  >>> value.hex(':')
  'b9:01:ef'
  >>> value.hex(':', 2)
  'b9:01ef'
  >>> value.hex(':', -2)
  'b901:ef'
index(...)

  B.index(sub[, start[, end]]) -> int

  Return the lowest index in B where subsection sub is found,
  such that sub is contained within B[start,end].  Optional
  arguments start and end are interpreted as in slice notation.

  Raises ValueError when the subsection is not found.
isalnum(...)

  B.isalnum() -> bool

  Return True if all characters in B are alphanumeric
  and there is at least one character in B, False otherwise.
isalpha(...)

  B.isalpha() -> bool

  Return True if all characters in B are alphabetic
  and there is at least one character in B, False otherwise.
isascii(...)

  B.isascii() -> bool

  Return True if B is empty or all characters in B are ASCII,
  False otherwise.
isdigit(...)

  B.isdigit() -> bool

  Return True if all characters in B are digits
  and there is at least one character in B, False otherwise.
islower(...)

  B.islower() -> bool

  Return True if all cased characters in B are lowercase and there is
  at least one cased character in B, False otherwise.
isspace(...)

  B.isspace() -> bool

  Return True if all characters in B are whitespace
  and there is at least one character in B, False otherwise.
istitle(...)

  B.istitle() -> bool

  Return True if B is a titlecased string and there is at least one
  character in B, i.e. uppercase characters may only follow uncased
  characters and lowercase characters only cased ones. Return False
  otherwise.
isupper(...)

  B.isupper() -> bool

  Return True if all cased characters in B are uppercase and there is
  at least one cased character in B, False otherwise.
join(self, iterable_of_bytes, /)

  Concatenate any number of bytes objects.

  The bytes whose method is called is inserted in between each pair.

  The result is returned as a new bytes object.

  Example: b'.'.join([b'ab', b'pq', b'rs']) -> b'ab.pq.rs'.
ljust(self, width, fillchar=b' ', /)

  Return a left-justified string of length width.

  Padding is done using the specified fill character.
lower(...)

  B.lower() -> copy of B

  Return a copy of B with all ASCII characters converted to lowercase.
lstrip(self, bytes=None, /)

  Strip leading bytes contained in the argument.

  If the argument is omitted or None, strip leading  ASCII whitespace.
maketrans(frm, to, /)

  Return a translation table useable for the bytes or bytearray translate method.

  The returned table will be one where each byte in frm is mapped to the byte at
  the same position in to.

  The bytes objects frm and to must be of the same length.
partition(self, sep, /)

  Partition the bytes into three parts using the given separator.

  This will search for the separator sep in the bytes. If the separator is found,
  returns a 3-tuple containing the part before the separator, the separator
  itself, and the part after it.

  If the separator is not found, returns a 3-tuple containing the original bytes
  object and two empty bytes objects.
removeprefix(self, prefix, /)

  Return a bytes object with the given prefix string removed if present.

  If the bytes starts with the prefix string, return bytes[len(prefix):].
  Otherwise, return a copy of the original bytes.
removesuffix(self, suffix, /)

  Return a bytes object with the given suffix string removed if present.

  If the bytes ends with the suffix string and that suffix is not empty,
  return bytes[:-len(prefix)].  Otherwise, return a copy of the original
  bytes.
replace(self, old, new, count=-1, /)

  Return a copy with all occurrences of substring old replaced by new.

    count
      Maximum number of occurrences to replace.
      -1 (the default value) means replace all occurrences.

  If the optional argument count is given, only the first count occurrences are
  replaced.
rfind(...)

  B.rfind(sub[, start[, end]]) -> int

  Return the highest index in B where subsection sub is found,
  such that sub is contained within B[start,end].  Optional
  arguments start and end are interpreted as in slice notation.

  Return -1 on failure.
rindex(...)

  B.rindex(sub[, start[, end]]) -> int

  Return the highest index in B where subsection sub is found,
  such that sub is contained within B[start,end].  Optional
  arguments start and end are interpreted as in slice notation.

  Raise ValueError when the subsection is not found.
rjust(self, width, fillchar=b' ', /)

  Return a right-justified string of length width.

  Padding is done using the specified fill character.
rpartition(self, sep, /)

  Partition the bytes into three parts using the given separator.

  This will search for the separator sep in the bytes, starting at the end. If
  the separator is found, returns a 3-tuple containing the part before the
  separator, the separator itself, and the part after it.

  If the separator is not found, returns a 3-tuple containing two empty bytes
  objects and the original bytes object.
rsplit(self, /, sep=None, maxsplit=-1)

  Return a list of the sections in the bytes, using sep as the delimiter.

    sep
      The delimiter according which to split the bytes.
      None (the default value) means split on ASCII whitespace characters
      (space, tab, return, newline, formfeed, vertical tab).
    maxsplit
      Maximum number of splits to do.
      -1 (the default value) means no limit.

  Splitting is done starting at the end of the bytes and working to the front.
rstrip(self, bytes=None, /)

  Strip trailing bytes contained in the argument.

  If the argument is omitted or None, strip trailing ASCII whitespace.
split(self, /, sep=None, maxsplit=-1)

  Return a list of the sections in the bytes, using sep as the delimiter.

    sep
      The delimiter according which to split the bytes.
      None (the default value) means split on ASCII whitespace characters
      (space, tab, return, newline, formfeed, vertical tab).
    maxsplit
      Maximum number of splits to do.
      -1 (the default value) means no limit.
splitlines(self, /, keepends=False)

  Return a list of the lines in the bytes, breaking at line boundaries.

  Line breaks are not included in the resulting list unless keepends is given and
  true.
startswith(...)

  B.startswith(prefix[, start[, end]]) -> bool

  Return True if B starts with the specified prefix, False otherwise.
  With optional start, test B beginning at that position.
  With optional end, stop comparing B at that position.
  prefix can also be a tuple of bytes to try.
strip(self, bytes=None, /)

  Strip leading and trailing bytes contained in the argument.

  If the argument is omitted or None, strip leading and trailing ASCII whitespace.
swapcase(...)

  B.swapcase() -> copy of B

  Return a copy of B with uppercase ASCII characters converted
  to lowercase ASCII and vice versa.
title(...)

  B.title() -> copy of B

  Return a titlecased version of B, i.e. ASCII words start with uppercase
  characters, all remaining cased characters have lowercase.
translate(self, table, /, delete=b'')

  Return a copy with each character mapped by the given translation table.

    table
      Translation table, which must be a bytes object of length 256.

  All characters occurring in the optional argument delete are removed.
  The remaining characters are mapped through the given translation table.
upper(...)

  B.upper() -> copy of B

  Return a copy of B with all ASCII characters converted to uppercase.
zfill(self, width, /)

  Pad a numeric string with zeros on the left, to fill a field of the given width.

  The original string is never truncated.

int

int([x]) -> integer
int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments
are given.  If x is a number, return x.__int__().  For floating point
numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base.  The literal can be preceded by '+' or '-' and be surrounded
by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
as_integer_ratio(self, /)

  Return integer ratio.

  Return a pair of integers, whose ratio is exactly equal to the original int
  and with a positive denominator.

  >>> (10).as_integer_ratio()
  (10, 1)
  >>> (-10).as_integer_ratio()
  (-10, 1)
  >>> (0).as_integer_ratio()
  (0, 1)
bit_count(self, /)

  Number of ones in the binary representation of the absolute value of self.

  Also known as the population count.

  >>> bin(13)
  '0b1101'
  >>> (13).bit_count()
  3
bit_length(self, /)

  Number of bits necessary to represent self in binary.

  >>> bin(37)
  '0b100101'
  >>> (37).bit_length()
  6
conjugate(...)

  Returns self, the complex conjugate of any int.
from_bytes(bytes, byteorder, *, signed=False)

  Return the integer represented by the given array of bytes.

    bytes
      Holds the array of bytes to convert.  The argument must either
      support the buffer protocol or be an iterable object producing bytes.
      Bytes and bytearray are examples of built-in objects that support the
      buffer protocol.
    byteorder
      The byte order used to represent the integer.  If byteorder is 'big',
      the most significant byte is at the beginning of the byte array.  If
      byteorder is 'little', the most significant byte is at the end of the
      byte array.  To request the native byte order of the host system, use
      `sys.byteorder' as the byte order value.
    signed
      Indicates whether two's complement is used to represent the integer.
to_bytes(self, /, length, byteorder, *, signed=False)

  Return an array of bytes representing an integer.

    length
      Length of bytes object to use.  An OverflowError is raised if the
      integer is not representable with the given number of bytes.
    byteorder
      The byte order used to represent the integer.  If byteorder is 'big',
      the most significant byte is at the beginning of the byte array.  If
      byteorder is 'little', the most significant byte is at the end of the
      byte array.  To request the native byte order of the host system, use
      `sys.byteorder' as the byte order value.
    signed
      Determines whether two's complement is used to represent the integer.
      If signed is False and a negative integer is given, an OverflowError
      is raised.
denominator = <attribute 'denominator' of 'int' objects>
  the denominator of a rational number in lowest terms
imag = <attribute 'imag' of 'int' objects>
  the imaginary part of a complex number
numerator = <attribute 'numerator' of 'int' objects>
  the numerator of a rational number in lowest terms
real = <attribute 'real' of 'int' objects>
  the real part of a complex number

Functions

getnode

getnode()

  Get the hardware address as a 48-bit positive integer.

      The first time this runs, it may launch a separate program, which could
      be quite slow.  If all attempts to obtain the hardware address fail, we
      choose a random 48-bit number with its eighth bit set to 1 as recommended
      in RFC 4122.
    

uuid1

uuid1(node=None, clock_seq=None)

  Generate a UUID from a host ID, sequence number, and the current time.
      If 'node' is not given, getnode() is used to obtain the hardware
      address.  If 'clock_seq' is given, it is used as the sequence number;
      otherwise a random 14-bit sequence number is chosen.

uuid3

uuid3(namespace, name)

  Generate a UUID from the MD5 hash of a namespace UUID and a name.

uuid4

uuid4()

  Generate a random UUID.

uuid5

uuid5(namespace, name)

  Generate a UUID from the SHA-1 hash of a namespace UUID and a name.

Other members

NAMESPACE_DNS = UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')
NAMESPACE_OID = UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8')
NAMESPACE_URL = UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8')
NAMESPACE_X500 = UUID('6ba7b814-9dad-11d1-80b4-00c04fd430c8')
RESERVED_FUTURE = 'reserved for future definition'
RESERVED_MICROSOFT = 'reserved for Microsoft compatibility'
RESERVED_NCS = 'reserved for NCS compatibility'
RFC_4122 = 'specified in RFC 4122'

Modules

os

platform

sys