import json
import datetime
def attach_metadata(entry, metadata_source, override_values=None):
"""
Attaches metadata to an entry, allowing for manual overrides.
Args:
entry (dict): The entry dictionary to which metadata will be attached.
metadata_source (dict): A dictionary containing the metadata to be attached.
override_values (dict, optional): A dictionary of metadata keys and their
manual override values. Defaults to None.
Returns:
dict: The entry dictionary with attached metadata. Returns the original entry if metadata_source is empty.
"""
if not metadata_source:
return entry
# Merge metadata, prioritizing overrides
merged_metadata = metadata_source.copy()
if override_values:
merged_metadata.update(override_values) # Overwrite with provided values
# Add timestamp
merged_metadata["timestamp"] = datetime.datetime.now().isoformat()
# Attach metadata to the entry
entry.update(merged_metadata)
return entry
if __name__ == '__main__':
# Example Usage
entry = {"id": 123, "data": "some data"}
metadata_source = {
"source": "system",
"user": "john.doe",
"environment": "production"
}
override_values = {
"user": "jane.doe", # Override user
"environment": "staging" # Override environment
}
updated_entry = attach_metadata(entry, metadata_source, override_values)
print(json.dumps(updated_entry, indent=4))
# Example with no overrides
entry2 = {"id": 456, "data": "another data"}
metadata_source2 = {
"source": "system",
"user": "john.doe",
"environment": "production"
}
updated_entry2 = attach_metadata(entry2, metadata_source2)
print(json.dumps(updated_entry2, indent=4))
#Example with empty metadata source
entry3 = {"id": 789, "data": "yet another data"}
metadata_source3 = {}
updated_entry3 = attach_metadata(entry3, metadata_source3)
print(json.dumps(updated_entry3, indent=4))
Add your comment