Here’s an updated version of the function that allows truncating the MD5 hash to a specified length based on an input argument. The function is optimized for readability, speed, and memory efficiency, with comments and a Google-style docstring.
import hashlib
def calculate_md5sum(file_path: str, truncate_length: int = None) -> str:
"""
Calculates the MD5 hash of a file and optionally truncates it to a specified length.
Args:
file_path (str): The path to the file for which the MD5 hash is to be calculated.
truncate_length (int, optional): The desired length of the truncated hash.
If None, the full hash is returned. Defaults to None.
Returns:
str: The MD5 hash of the file as a hexadecimal string, optionally truncated.
Raises:
FileNotFoundError: If the file at the specified path does not exist.
ValueError: If truncate_length is less than 1.
Example:
>>> calculate_md5sum('example.txt', truncate_length=8)
'd41d8cd9'
"""
if truncate_length is not None and truncate_length < 1:
raise ValueError("truncate_length must be greater than 0 or None.")
# Initialize the MD5 hash object
md5_hash = hashlib.md5()
try:
# Open the file in binary mode to handle all types of files
with open(file_path, "rb") as file:
# Read the file in chunks to optimize memory usage
# 64KB chunks are a good balance between speed and memory efficiency
for chunk in iter(lambda: file.read(65536), b""):
md5_hash.update(chunk)
except FileNotFoundError:
raise FileNotFoundError(f"The file at path '{file_path}' does not exist.")
# Get the full MD5 hash as a hexadecimal string
full_hash = md5_hash.hexdigest()
# Truncate the hash if truncate_length is specified
if truncate_length is not None:
return full_hash[:truncate_length]
else:
return full_hash
Key Updates:
- Truncation Feature: Added an optional
truncate_length parameter to truncate the hash to a specified length.
- Error Handling: Added a check to ensure
truncate_length is valid (greater than 0 or None).
- Docstring Update: Updated the docstring to include the new parameter and its behavior.
Usage Examples:
# Full MD5 hash
full_hash = calculate_md5sum('path/to/your/file.txt')
print(f"Full MD5 Hash: {full_hash}")
# Truncated MD5 hash
truncated_hash = calculate_md5sum('path/to/your/file.txt', truncate_length=8)
print(f"Truncated MD5 Hash: {truncated_hash}")
This implementation maintains efficiency while adding flexibility for truncating the hash.