Mathew K Analytics

Lesson 23 · Python standard library deep dive

Python uuid, base64 & binascii Explained: Encode Anything | Standard Library #23

Video twenty-three of the twenty-five-part series: uuid, base64, and binascii, for unique identifiers and binary/text encoding. Random and deterministic…

⬇ Download notebookOpen in Colab ↗

📓 Full notebook

Download .ipynb

Python Standard Library Deep-Dive, Video 23: uuid, base64, binascii#

  • Video twenty-three of the twenty-five-part series: uuid, base64, and binascii, for unique identifiers and binary/text encoding.
  • Random and deterministic UUIDs, base64 encoding for binary-safe text, and low-level binary/hex conversions.
  • Let's get into it.

Part 1: Why Unique Identifiers, and uuid4()#

import uuid
id1 = uuid.uuid4()
id2 = uuid.uuid4()
print(id1)
print(id2)
print(id1 == id2)
print(type(id1))
43fe0834-7cde-4dc1-a46f-d7f08bb58696
8e9f9889-fe22-4d1b-9354-8e30800ca850
False
<class 'uuid.UUID'>

Part 2: uuid1() and Deterministic uuid3()/uuid5()#

time_based = uuid.uuid1()
print(time_based)
name_uuid_1 = uuid.uuid5(uuid.NAMESPACE_DNS, 'example.com')
name_uuid_2 = uuid.uuid5(uuid.NAMESPACE_DNS, 'example.com')
print(name_uuid_1)
print(name_uuid_1 == name_uuid_2)
different_name = uuid.uuid5(uuid.NAMESPACE_DNS, 'other.com')
print(name_uuid_1 == different_name)
0fd82b31-9ef4-11f1-a1e9-a059505abbcf
cfbff0d1-9375-5685-968c-48ce8b15ae17
True
False

Part 3: UUID Object Attributes#

sample = uuid.uuid4()
print(sample.hex)
print(len(sample.hex))
print(sample.int > 0)
print(len(sample.bytes))
print(sample.version)
print(uuid.UUID(sample.hex) == sample)
fca15ca8da6846cf9a355f7ef307b783
32
True
16
4
True

Part 4: base64.b64encode() and b64decode()#

import base64
raw_data = b'Hello, this is genuinely raw binary-ish data!'
encoded = base64.b64encode(raw_data)
print(encoded)
print(type(encoded))
decoded = base64.b64decode(encoded)
print(decoded)
print(decoded == raw_data)
b'SGVsbG8sIHRoaXMgaXMgZ2VudWluZWx5IHJhdyBiaW5hcnktaXNoIGRhdGEh'
<class 'bytes'>
b'Hello, this is genuinely raw binary-ish data!'
True

Part 5: base64.urlsafe_b64encode() and urlsafe_b64decode()#

binary_id = uuid.uuid4().bytes
standard = base64.b64encode(binary_id)
urlsafe = base64.urlsafe_b64encode(binary_id)
print(standard)
print(urlsafe)
print(base64.urlsafe_b64decode(urlsafe) == binary_id)
b'aIiGSRxoQreFODTCRKH/xA=='
b'aIiGSRxoQreFODTCRKH_xA=='
True

Part 6: base64 with Real Binary Files#

with open('demo_binary.bin', 'wb') as f:
    f.write(bytes([0, 1, 2, 255, 254, 253, 128]))
with open('demo_binary.bin', 'rb') as f:
    file_bytes = f.read()
encoded_file = base64.b64encode(file_bytes).decode('ascii')
print(encoded_file)
import json
payload = json.dumps({'filename': 'demo_binary.bin', 'content': encoded_file})
print(payload)
restored = json.loads(payload)
restored_bytes = base64.b64decode(restored['content'])
print(restored_bytes == file_bytes)
AAEC//79gA==
{"filename": "demo_binary.bin", "content": "AAEC//79gA=="}
True

Part 7: binascii.hexlify() and unhexlify()#

import binascii
raw = b'\x00\x01\xfe\xff'
hexed = binascii.hexlify(raw)
print(hexed)
print(hexed.decode('ascii'))
restored_bytes = binascii.unhexlify(hexed)
print(restored_bytes == raw)
b'0001feff'
0001feff
True

Part 8: binascii.crc32() - a Fast Checksum#

data_v1 = b'original file content'
data_v2 = b'original file content!'
checksum1 = binascii.crc32(data_v1)
checksum2 = binascii.crc32(data_v2)
print(checksum1)
print(checksum2)
print(checksum1 == binascii.crc32(data_v1))
2518377769
3696196826
True

Part 9: A Real Pattern - Generating Unique Filenames#

def unique_filename(original_name):
    ext = original_name.rsplit('.', 1)[-1] if '.' in original_name else ''
    unique_part = uuid.uuid4().hex
    return f'{unique_part}.{ext}' if ext else unique_part
print(unique_filename('photo.jpg'))
print(unique_filename('photo.jpg'))
print(unique_filename('README'))
485669871ab24950b86e3066eac48a3d.jpg
54b3eb3b7c1b494e8b7654d308db039f.jpg
2b0892242d3f407e89bea68c0dee4608

Part 10: A Real Pattern - Building a Basic Auth Header#

def build_basic_auth_header(username, password):
    credentials = f'{username}:{password}'
    encoded_credentials = base64.b64encode(credentials.encode('utf-8')).decode('ascii')
    return f'Basic {encoded_credentials}'
header = build_basic_auth_header('ana', 'sup3rs3cret')
print(header)
def decode_basic_auth_header(header_value):
    scheme, encoded = header_value.split(' ', 1)
    decoded = base64.b64decode(encoded).decode('utf-8')
    username, password = decoded.split(':', 1)
    return username, password
print(decode_basic_auth_header(header))
Basic YW5hOnN1cDNyczNjcmV0
('ana', 'sup3rs3cret')

Wrap-Up: What You Learned#

  • uuid4 generates a random 128-bit identifier; collisions are astronomically unlikely.
  • uuid1 embeds timestamp and machine info; uuid3/uuid5 are deterministic, hashing a namespace plus a name.
  • UUID objects expose .hex, .int, .bytes, and .version for different representations of the same value.
  • base64.b64encode/b64decode convert arbitrary binary data to and from safe ASCII text; it's encoding, not encryption.
  • urlsafe_b64encode/decode swap +/ for -_ so the result can be embedded directly in a URL.
  • base64 lets binary file content be safely embedded inside text formats like JSON.
  • binascii.hexlify/unhexlify convert raw bytes to and from hex text; it's the lower-level tool base64 builds on.
  • binascii.crc32 gives a fast, compact checksum for corruption detection; never substitute it for a real cryptographic hash.
  • A real pattern: uuid4 for collision-free generated filenames.
  • A real pattern: building and decoding an HTTP Basic Authentication header with base64.
  • That wraps up uuid, base64, and binascii. Next up: abc and inspect, for abstract base classes and introspection.

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.