function extract_uid
Extracts a UID (Unique Identifier) from an object or dictionary by checking both 'uid' and 'UID' properties, returning a string representation or a default value if not found.
/tf/active/vicechatdev/CDocs/utils/uid_helper.py
28 - 60
simple
Purpose
This utility function provides a flexible way to extract UID values from various object types (dictionaries, objects with attributes) while handling case variations ('uid' vs 'UID'). It's useful in systems where UIDs may be stored with inconsistent casing or in different data structures, ensuring robust UID retrieval with fallback support.
Source Code
def extract_uid(obj, default=None):
"""
Extract UID from an object, checking both 'uid' and 'UID' properties.
Parameters
----------
obj : dict or object
Object or dictionary to extract UID from
default : str, optional
Default value if no UID found
Returns
-------
str
Extracted UID or default
"""
if not obj:
return default
# For dictionary-like objects
if hasattr(obj, 'get'):
uid = obj.get('UID') or obj.get('uid')
if uid:
return str(uid)
# For object attributes
for attr in ['UID', 'uid']:
if hasattr(obj, attr):
uid = getattr(obj, attr)
if uid:
return str(uid)
return default
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
obj |
- | - | positional_or_keyword |
default |
- | None | positional_or_keyword |
Parameter Details
obj: The source object or dictionary from which to extract the UID. Can be a dictionary-like object with a 'get' method, an object with 'uid' or 'UID' attributes, or None. The function handles both dictionary access patterns and object attribute access patterns.
default: Optional fallback value to return if no UID is found in the object. Defaults to None. This allows callers to specify a custom default value when UID extraction fails, providing flexibility in error handling.
Return Value
Returns a string representation of the extracted UID if found in the object (either as 'UID' or 'uid' key/attribute). If no UID is found or the object is falsy (None, empty dict, etc.), returns the default value. The UID is always converted to a string before returning, ensuring consistent return type.
Usage Example
# Example 1: Extract from dictionary
user_dict = {'UID': '12345', 'name': 'John'}
uid = extract_uid(user_dict)
print(uid) # Output: '12345'
# Example 2: Extract from object with attribute
class User:
def __init__(self, uid):
self.uid = uid
user_obj = User('67890')
uid = extract_uid(user_obj)
print(uid) # Output: '67890'
# Example 3: Handle missing UID with default
empty_dict = {}
uid = extract_uid(empty_dict, default='unknown')
print(uid) # Output: 'unknown'
# Example 4: Handle None object
uid = extract_uid(None, default='N/A')
print(uid) # Output: 'N/A'
# Example 5: Case-insensitive extraction
data = {'uid': 'abc123'} # lowercase
uid = extract_uid(data)
print(uid) # Output: 'abc123'
Best Practices
- Always provide a meaningful default value when calling this function if you need to handle missing UIDs gracefully
- The function prioritizes 'UID' (uppercase) over 'uid' (lowercase) in both dictionary and attribute lookups
- The function returns None by default if no UID is found and no default is specified, so check for None in calling code if needed
- The returned UID is always converted to a string, so numeric UIDs will be stringified
- The function returns early if the object is falsy (None, empty, etc.), making it safe to use with potentially null objects
- For dictionary-like objects, the function uses the 'get' method which is safer than direct key access and won't raise KeyError
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function normalize_uid 53.1% similar
-
function get_node_by_uid 49.1% similar
-
function get_document_versions_from_db_v1 44.6% similar
-
function get_document 43.8% similar
-
function get_document_versions_from_db_v6 43.4% similar