U UniCore Community Public content rendered for search, speed, and sharing

Documentation

Object Functions

Utilities for dictionaries and object-like structures.

Utilities for working with objects and dictionaries.

keys()

Returns the keys of a dictionary as a list

Implementation

Wraps dict.keys() with list conversion

Example

keys = UniCoreFW.keys({"name": "John", "age": 30})

Expected output: ["name", "age"]

Source Code

def keys(obj):
    return list(obj.keys())

to_dict()

Convert a value to a dictionary.

Implementation

Args: value: The value to convert to a dictionary.

Returns:
    A dictionary representation of the given value.

Example

to_dict([1, 2, 3])

Expected output: {0: 1, 1: 2, 2: 3}

Source Code

def to_dict(value):
    if isinstance(value, dict):
        return value
    if isinstance(value, (list, tuple)):
        return {i: v for i, v in enumerate(value)}
    if hasattr(value, "items") and callable(getattr(value, "items")):
        return dict(value.items())
    try:
        return dict(value)  # best-effort
    except Exception:
        return {}

to_list()

Casts a value to a list: None -> [], tuples/sets -> list, others -> [value].

Implementation

Args: value: The value to convert to a list.

Returns:
    List representation of the given `value`, or an empty list if `value` is None.

Example

to_list(123)

Expected output: [123]

Source Code

def to_list(value: Any) -> List[Any]:
    if value is None:
        return []
    if isinstance(value, list):
        return value
    if isinstance(value, (tuple, set)):
        return list(value)
    return [value]

to_string()

Converts the given value to a string.

Implementation

Args: value: The value to convert to a string.

Returns:
    String representation of the given `value`, or an empty string if `value` is None.

Example

to_string(123)

Expected output: '123'

Source Code

def to_string(value: Any) -> str:

    return "" if value is None else str(value)

to_integer()

Converts value to an integer. If conversion fails, returns 0.

Implementation

Args: value: The value to convert to an integer.

Returns:
    Integer representation of the given value, or 0 if conversion fails.

Example

to_integer(3.7)

Expected output: 3

Source Code

def to_integer(value: Any) -> int:

    try:
        return int(float(value))
    except Exception:
        return 0

rename_keys()

Rename the keys of obj using key_map and return new object.

Implementation

Args: obj: Object to rename. key_map: Renaming map whose keys correspond to existing keys in obj and whose values are the new key name.

Returns:
    Renamed obj.

Example

obj = rename_keys({"a": 1, "b": 2, "c": 3}, {"a": "A", "b": "B"})
obj == {"A": 1, "B": 2, "c": 3}

Expected output: True

Source Code

def rename_keys(obj: Dict[Any, Any], key_map: Dict[Any, Any]) -> Dict[Any, Any]:
    return {key_map.get(k, k): v for k, v in obj.items()}

map_values()

Creates a new dictionary with the same keys but values generated by running each value of the input dictionary through the given iteratee.

Implementation

Args: obj: The dictionary to process. iteratee: A function or a string key used to generate the new values. If a string is provided, it is used to access the given key of each value in the dictionary.

Returns:
    A new dictionary with the original keys and values generated by the iteratee.

Example

map_values({"a": {"b": 1}, "c": {"b": 2}}, "b")

Expected output: {'a': 1, 'c': 2}

Source Code

def map_values(
    obj: Dict[Any, Any], iteratee: Union[str, Callable[[Any], Any]]
) -> Dict[Any, Any]:

    if isinstance(iteratee, str):

        def fn(v):
            return (
                v.get(iteratee) if isinstance(v, dict) else getattr(v, iteratee, None)
            )
    else:
        fn = iteratee  # type: ignore
    return {k: fn(v) for k, v in obj.items()}

map_keys()

Creates an object with the same values but keys generated by running each key through iteratee.

Implementation

Args: obj: The dictionary to process. iteratee: A function or a string key used to generate the new keys. If a string is provided, it is used to access the given key of each value in the dictionary.

Returns:
    A new dictionary with values generated by iteratee as keys and original values as values.

Example

map_keys({"a": {"b": 1}, "c": {"b": 2}}, "b")

Expected output: {1: {"b": 1}, 2: {"b": 2}}

Source Code

def map_keys(
    obj: Dict[Any, Any], iteratee: Union[str, Callable[[Any], Any]]
) -> Dict[Any, Any]:
    if isinstance(iteratee, str):

        def fn(k, v):
            return (
                v.get(iteratee) if isinstance(v, dict) else getattr(v, iteratee, None)
            )
    else:
        fn = iteratee  # type: ignore
    out: Dict[Any, Any] = {}
    for k, v in obj.items():
        out[fn(k, v)] = v
    return out

assign()

Assigns properties of source object(s) to the destination object.

Implementation

Args: target: Destination object whose properties will be modified. sources: Source objects to assign to target.

Returns:
    Modified `target`.

Warning:
    `target` is modified in place.

Example

obj = {}
obj2 = assign(obj, {"a": 1}, {"b": 2}, {"c": 3})
obj == {"a": 1, "b": 2, "c": 3}

Expected output: True

Source Code

def assign(target: Dict[Any, Any], *sources: Dict[Any, Any]) -> Dict[Any, Any]:
    for src in sources:
        for k, v in src.items():
            target[k] = v
    return target

sample_size()

Retrieves n random elements from a given collection.

Implementation

The last element of the returned list would be the result of using :func:sample.

Example

sample_size([1, 2, 3, 4], 2)

Expected output: [2, 4]

Source Code

def sample_size(
    collection: Union[Dict[Any, Any], List[Any]], n: Optional[int] = None
) -> List[Any]:
    items = (
        list(collection.values()) if isinstance(collection, dict) else list(collection)
    )
    length = len(items)
    if n is None or n < 0:
        n = 1
    n = min(n, length)
    return random.sample(items, n)

reductions_right()

Applies a rolling computation to sequential pairs of values in an iterable from right to left.

Implementation

Args: collection: An iterable to be reduced. func: A binary function to be applied to the items of the iterable. initializer: An initial value for the accumulator.

Returns:
    A list of accumulated values.

Example

reductions_right([1, 2, 3, 4], lambda x, y: x + y, 0)

Expected output: [10, 9, 7, 4]

Source Code

def reductions_right(
    collection: Union[Dict[Any, Any], List[Any]], func: Callable, initial: Any
) -> List[Any]:
    acc = initial
    result: List[Any] = []
    items = (
        list(collection.values()) if isinstance(collection, dict) else list(collection)
    )
    for v in reversed(items):
        acc = func(acc, v)
        result.append(acc)
    return result

reductions()

Applies a rolling computation to sequential pairs of values in an iterable.

Implementation

Args: collection: An iterable to be reduced. func: A binary function to be applied to the items of the iterable. initializer: An initial value for the accumulator.

Returns:
    A list of accumulated values.

Example

reductions([1, 2, 3, 4], lambda x, y: x + y, 0)

Expected output: [1, 3, 6, 10]

Source Code

def reductions(
    collection: Union[Dict[Any, Any], List[Any]], func: Callable, initial: Any
) -> List[Any]:
    acc = initial
    result: List[Any] = []
    items = collection.values() if isinstance(collection, dict) else collection
    for v in items:
        acc = func(acc, v)
        result.append(acc)
    return result

reduce_right()

Reduces a collection to a single accumulated value by applying a function from right to left.

Implementation

Args: collection: The collection to reduce, can be a dictionary or a list. func: A function that takes two arguments, the accumulator and the current value, and returns an updated accumulator. initial: The initial value for the accumulator.

Returns:
    The final accumulated value after applying the function to all elements in the collection in reverse order.

Example

reduce_right([1, 2, 3, 4], lambda acc, x: acc + x, 0)

Expected output: 10

Source Code

def reduce_right(
    collection: Union[Dict[Any, Any], List[Any]], func: Callable, initial: Any
) -> Any:
    acc = initial
    items = (
        list(collection.values()) if isinstance(collection, dict) else list(collection)
    )
    for v in reversed(items):
        acc = func(acc, v)
    return acc

order_by()

Orders a collection of dictionaries based on the specified iteratees and their corresponding orders.

Implementation

Args: collection: The list of dictionaries to be ordered. iteratees: A list of iteratees to sort by. Each iteratee can be a string representing a key in the dictionaries or a callable that extracts a value from each element. orders: An optional list of sort orders corresponding to each iteratee. Each order can be 'asc' for ascending or 'desc' for descending. If not provided, all iteratees will default to 'asc'.

Returns:
    A new list of dictionaries sorted according to the specified iteratees and orders.

Example

items = [{'a': 2, 'b': 3}, {'a': 1, 'b': 4}]
order_by(items, ['a'], ['asc'])

Expected output: [{'a': 1, 'b': 4}, {'a': 2, 'b': 3}]

Source Code

def order_by(
    collection: List[Dict[Any, Any]],
    iteratees: List[Union[str, Callable]],
    orders: Optional[List[str]] = None,
) -> List[Dict[Any, Any]]:

    result = list(collection)
    orders = orders or ["asc"] * len(iteratees)
    for key_fn, order in reversed(list(zip(iteratees, orders))):
        if isinstance(key_fn, str):

            def fn(x, field=key_fn):
                return x.get(field)
        else:
            fn = key_fn
        result.sort(key=fn, reverse=(order == "desc"))
    return result

values()

Returns the values of a dictionary as a list

Implementation

Wraps dict.values() with list conversion

Example

values = UniCoreFW.values({"name": "John", "age": 30})

Expected output: ["John", 30]

Source Code

def values(obj):
    return list(obj.values())

to_pairs()

Convert obj into an array of [key, value] pairs.

Implementation

Args: obj: The dictionary, list, tuple, or other object to convert

Returns:
    A list of key-value tuples

Example

to_pairs({"a": 1, "b": 2})

Expected output: [("a", 1), ("b", 2)]

Source Code

def to_pairs(obj) -> list:
    return list(_iter_items_like(obj))

clone()

Creates a shallow copy of an object

Implementation

Uses dict.copy() or list() depending on the type

Example

cloned = UniCoreFW.clone({"name": "John", "age": 30})

Expected output: {"name": "John", "age": 30} (shallow copy)

Source Code

def clone(obj):
    if isinstance(obj, dict):
        return obj.copy()
    elif isinstance(obj, list):
        return list(obj)
    else:
        return obj

apply_catch()

Apply a function while catching exceptions.

Implementation

Preferred: apply_catch(value, fn, exceptions | (exceptions,), default=None) Legacy: apply_catch(fn, *args, default=None, exceptions=Exception)

Args:
    *args: The arguments to apply the function to.
    **kwargs: The keyword arguments to apply the function with.

Returns:
    The result of the function, or None if the predicate is false.

Example

apply_catch(1, lambda x: x + 1, lambda x: x > 0)

Expected output: 2

Source Code

def apply_catch(*args, default=None, exceptions=Exception, **kwargs):
    if isinstance(exceptions, (list, set)):
        exceptions = tuple(exceptions)
    if not isinstance(exceptions, tuple) and isinstance(exceptions, type):
        exc_types = exceptions
    else:
        try:
            exc_types = tuple(exceptions)  # type: ignore
        except TypeError:
            exc_types = Exception

    # value-first
    if args and not callable(args[0]) and len(args) >= 2 and callable(args[1]):
        value, fn = args[0], args[1]
        try:
            return fn(value)
        except exc_types:
            return value if default is None else default

    # legacy
    fn, *fargs = args # type: ignore
    try:
        return fn(*fargs, **kwargs)  # type: ignore
    except exc_types:
        return default

apply_if()

Apply a function to a value only if predicate(value) is True.

Implementation

Accepted forms: - value-first (preferred): apply_if(value, fn, predicate) - legacy: apply_if(fn, predicate, args, *kwargs)

Args:
    *args: The arguments to apply the function to.
    **kwargs: The keyword arguments to apply the function with.

Returns:
    The result of the function, or None if the predicate is false.

Example

apply_if(1, lambda x: x + 1, lambda x: x > 0)

Expected output: 2

Source Code

def apply_if(*args, **kwargs):
    if args and not callable(args[0]) and len(args) >= 2 and callable(args[1]):
        value, fn, predicate = args[0], args[1], args[2]
        return fn(value) if predicate(value) else value
    fn, predicate, *rest = args # type: ignore
    return fn(*rest, **kwargs) if predicate(*rest, **kwargs) else None

update_with()

Update value at path by applying func (or using it as a constant).

Implementation

Args: obj: The object to modify. path: The path of the property to update. func: Function that returns updated value. customizer: The function to customize assigned values.

Returns:
    Modified `obj`.

Warning:
    `obj` is modified in place.

Example

obj = {"a": [{"b": {"c": 7}}]}
update_with(obj, "a[0].b.c", lambda x: x**2, dict)

Expected output: {'a': [{'b': {'c': 49}}]}

Source Code

def update_with(obj, path, func, customizer):
    current = get(obj, path)
    if callable(func):
        try:
            new_val = func(current)
        except TypeError:
            new_val = func()
    else:
        new_val = func
    return set_with(obj, path, new_val, customizer)

set_with()

Set value at path, creating intermediate containers. Supports escaped dots and bracket literals via _as_parts_any(). If customizer is callable, it's invoked to produce the objects of path. If customizer returns undefined path creation is handled by the method instead. The customizer is invoked with three arguments: (nested_value, key, nested_object).

Implementation

Args: obj: Object to modify. path: The path to set value to. value: The value to set. customizer: The function to customize assigned values.

Returns:
    Modified `obj`.

Warning:
    `obj` is modified in place.

Example

set_with({}, "[0][1]", "a", lambda: {})

Expected output: {0: {1: 'a'}}

Source Code

def set_with(obj, path, value, customizer):
    def make():
        if callable(customizer):
            return customizer()
        if isinstance(customizer, list):
            return []
        return {}

    parts = _parse_path(path) if isinstance(path, str) else ([path] if isinstance(path, int) else list(path))
    cur = obj
    for i, seg in enumerate(parts):
        last = (i == len(parts) - 1)
        if last:
            if isinstance(cur, list) and isinstance(seg, int):
                while len(cur) <= seg:
                    cur.append(None)
                cur[seg] = value
            elif isinstance(cur, dict):
                cur[seg] = value
            else:
                setattr(cur, str(seg), value)
            return obj

        # Not last: descend, creating with customizer only when needed
        if isinstance(cur, list) and isinstance(seg, int):
            while len(cur) <= seg:
                cur.append(None)
            child = cur[seg]
            if not _is_containerish(child):
                child = make()
                cur[seg] = child
            cur = child
        elif isinstance(cur, dict):
            child = cur.get(seg, None)
            if not _is_containerish(child):
                child = make()
                cur[seg] = child
            cur = child
        else:
            sentinel = _MISSING
            child = getattr(cur, str(seg), sentinel)
            if child is sentinel or not _is_containerish(child):
                child = make()
                setattr(cur, str(seg), child)
            cur = child

    return obj

set_()

Set value at path, creating intermediate containers. Supports escaped dots and bracket literals via _as_parts_any().

Implementation

Args: obj: The object to modify. path: The path of the property to set. value: The value to set.

Returns:
    Updated `obj`.

Example

obj = {"a": [{"b": {"c": 7}}]}
set_(obj, "a[0].b.c", 8)

Expected output: {'a': [{'b': {'c': 8}}]}

Source Code

def set_(obj, path, value):
    parts = _as_parts_any(path)
    if not parts:
        return obj

    cur = obj
    for i, seg in enumerate(parts[:-1]):
        prefer_list = isinstance(parts[i + 1], int)
        if isinstance(cur, dict):
            cur, _ = _ensure_container(cur, seg, None, prefer_list_index=prefer_list)
        elif isinstance(cur, list) and isinstance(seg, int):
            cur, _ = _ensure_container(cur, seg, None, prefer_list_index=prefer_list)
        else:
            cur, _ = _ensure_container(cur, str(seg), None, prefer_list_index=prefer_list)

    last = parts[-1]
    if isinstance(cur, dict):
        cur[last] = value
    elif isinstance(cur, list) and isinstance(last, int):
        while len(cur) <= last:
            cur.append(None)
        cur[last] = value
    else:
        setattr(cur, str(last), value)
    return obj

to_number()

Convert value to a number. All numbers are retuned as float. If precision is negative, round value to the nearest positive integer place. If value can't be converted to a number, None is returned.

Implementation

Args: value: Object to convert. precision: Precision to round number to. Defaults to 0.

Returns:
    Converted number or ``None`` if it can't be converted.

Example

to_number("1234.5678")

Expected output: 1235.0

Source Code

def to_number(value: Any, precision: Optional[int] = 0) -> Optional[float]:
    try:
        num = float(value)
    except Exception:
        return None
    if precision is None:
        return num
    if precision >= 0:
        return round(num, precision)
    factor = 10 ** (-precision)
    return math.floor(num / factor) * factor

transform()

Transforms an object by applying a function to each item in the object.

Implementation

Args: obj: The object to transform func: A function to apply to each item in the object. It takes either 2 or 3 arguments depending on the type of the object. If obj is a dict, the arguments are (accumulator, value, key). If obj is a list, the arguments are (accumulator, value, index). If func returns False, the iteration will be stopped. accumulator: The initial accumulator value. If not provided, it will be set to an empty dict if obj is a dict, or an empty list if obj is a list

Returns:
    The accumulator after applying the function to all items in the object.

Example

transform({"a": 1, "b": 2}, lambda acc, v, k: acc.update({k: v + 1}))

Expected output: {"a": 2, "b": 3}

Source Code

def transform(
    obj: Union[Dict[Any, Any], List[Any]],
    func: Optional[Callable[..., Any]] = None,
    accumulator: Optional[Any] = None,
) -> Any:
    if accumulator is None:
        accumulator = {} if isinstance(obj, dict) else []
    if func is None:
        # No iteratee => leave accumulator unchanged
        return accumulator

    sig = inspect.signature(func)
    arity = sum(1 for p in sig.parameters.values()
                if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD))

    items = obj.items() if isinstance(obj, dict) else enumerate(obj)
    for k, v in items:
        res = func(accumulator, v, k) if arity >= 3 else func(accumulator, v)
        if res is False:
            break
    return accumulator

to_boolean()

Implementation

Implementation details are not available.

Example


Expected output: ``

Source Code

def to_boolean(
    value: Any,
    true_patterns: Optional[Iterable[str]] = None,
    false_patterns: Optional[Iterable[str]] = None,
) -> Optional[bool]:
    if isinstance(value, str):
        s = value.strip()
        if true_patterns:
            for p in true_patterns:
                if re.search(p, s, flags=re.IGNORECASE):
                    return True
        if false_patterns:
            for p in false_patterns:
                if re.search(p, s, flags=re.IGNORECASE):
                    return False
        if s == "":
            return None
        lower = s.lower()
        if lower in {"true", "1", "yes", "on"}:
            return True
        if lower in {"false", "0", "no", "off"}:
            return False
        return None
    return bool(value)

pick_by()

Creates an object composed of the picked object properties.

Implementation

Args: obj: Object to pick from. predicate: Predicate used to determine which properties to pick.

Returns:
    Object composed of picked properties.

Example

pick_by({"a": 1, "b": 2, "c": 3}, lambda v, k: k in ("a", "c"))

Expected output: {"a": 1, "c": 3}

Source Code

def pick_by(obj, predicate=None):
    if predicate is None:
        return to_dict(obj)
    if isinstance(predicate, (list, tuple, set)):
        keys = set(predicate)
        return {k: v for k, v in _iter_items_like(obj) if k in keys}
    if isinstance(predicate, str):
        key = predicate
        return {k: v for k, v in _iter_items_like(obj) if k == key}
    # callable(value, key)
    return {k: v for k, v in _iter_items_like(obj) if predicate(v, k)}

pick()

Creates an object composed of the picked keys_to_pick from obj.

Implementation

Args: obj: Object to pick from. *keys_to_pick: Keys to pick.

Returns:
    Object composed of picked keys.

Example

pick({"a": 1, "b": 2, "c": 3, "d": 4}, "a", "d")

Expected output: {"a": 1, "d": 4}

Source Code

def pick(obj, *keys_to_pick):
    if not keys_to_pick:
        return {}
    out: Dict[Any, Any] = {}
    deep_paths, flat_keys = [], set()

    for p in _flatten_keys(keys_to_pick):
        if isinstance(p, list) or (isinstance(p, str) and ('.' in p or '[' in p)):
            deep_paths.append(p)
        else:
            flat_keys.add(p)

    # single pass for top-level keys
    if flat_keys:
        for k, v in _iter_items_like(obj):
            if k in flat_keys:
                out[k] = v

    # deep paths
    for p in deep_paths:
        parts = p if isinstance(p, list) else _as_parts_any(p)
        val = get(obj, parts, _MISSING)
        if val is not _MISSING:
            _set_by_path(out, parts, val, obj)

    return out

parse_int()

Converts the given value into an integer of the specified radix. If radix is falsey, a radix of 10 is used unless the value is a hexadecimal, in which case a radix of 16 is used.

Implementation

Args: value: Value to parse. radix: Base to convert to.

Returns:
    Integer if parsable else ``None``.

Example

parse_int("5")

Expected output: 5

Source Code

def parse_int(value: Any, radix: Optional[int] = None) -> Optional[int]:
    if isinstance(value, bool):
        return int(value)

    # If no radix is specified, numbers parse naturally
    if radix is None and isinstance(value, (int, float)):
        try:
            return int(value)
        except Exception:
            return None

    # Otherwise parse the *string* with the requested base
    s = str(value).strip()
    try:
        base = 16 if radix is None else (0 if radix == 0 else radix)
        return int(s, base)
    except Exception:
        return None

merge_with()

Merges objects using a customizer.

Implementation

Args: *objects: Objects to merge. customizer: Customizer function. If None, falls back to merge.

Returns:
    Merged object.

Warning:
    Modified in place.

Example

merge_with({"a": 1}, {"b": 2}, lambda x, y, key, parent: x + y if key == "a" else y)

Expected output: {"a": 3, "b": 2}

Source Code

def merge_with(*objects, customizer=None):
    if customizer is None and objects and callable(objects[-1]):
        *objects, customizer = objects
    if not objects:
        return {}
    if customizer is None:
        return merge(*objects)

    def _call_c(obj_val, src_val, key=None, parent=None):
        try:
            return customizer(obj_val, src_val, key, parent)
        except TypeError:
            try:
                return customizer(obj_val, src_val, key)
            except TypeError:
                try:
                    return customizer(obj_val, src_val)
                except TypeError:
                    return customizer(src_val)

    def _merge(a, b, parent=None, key=None):
        # Give customizer first shot
        cv = _call_c(a, b, key, parent)
        if cv is not None:
            return cv

        # default deep behavior
        if isinstance(a, dict) and isinstance(b, dict):
            out = {k: clone_deep(v) if isinstance(v, (dict, list)) else v for k, v in a.items()} # type: ignore
            for k2, v2 in b.items():
                if k2 in out:
                    out[k2] = _merge(out[k2], v2, out, k2)
                else:
                    out[k2] = clone_deep(v2) if isinstance(v2, (dict, list)) else v2
            return out

        if isinstance(a, list) and isinstance(b, list):
            # default: element-wise (your merge semantics)
            m = max(len(a), len(b))
            out: List[Any] = []
            for i in range(m):
                if i < len(a) and i < len(b) and isinstance(a[i], dict) and isinstance(b[i], dict):
                    out.append(_merge(a[i], b[i], a, i))
                elif i < len(a) and i < len(b):
                    out.append(clone_deep(b[i]))
                elif i < len(a):
                    out.append(clone_deep(a[i]))
                else:
                    out.append(clone_deep(b[i]))
            return out

        # scalar or mismatched types: prefer b unless b is None
        if isinstance(b, (dict, list)):
            return clone_deep(b)
        return b if b is not None else a

    head, *rest = objects
    result = clone_deep(head) if isinstance(head, (dict, list)) else head
    for idx, nxt in enumerate(rest):
        result = _merge(result, nxt, None, None)
    return result

get()

Return the value at path from obj. If not set, returns default.

Implementation

Args: obj: Object to resolve the path on. path: The path to resolve. default: The value to return if path is not set.

Returns:
    The value at `path`, or `default`.

Example

get({"a": {"b": 1}}, "a.b")

Expected output: 1

Source Code

def get(obj: Any, path: Union[str, Iterable[Any], Any], default: Any = None) -> Any:
    parts = _as_parts_any(path)
    for p in parts:
        if isinstance(p, str) and p in _RESTRICTED:
            if isinstance(obj, (dict, list)):
                return default
            raise KeyError("access to restricted key")

    cur = obj
    for seg in parts:
        if cur is None:
            return default

        # dict
        if isinstance(cur, dict):
            if seg in cur:
                cur = cur[seg]
                continue
            # int<->str coercion
            if isinstance(seg, str) and _is_int_str(seg):
                i = int(seg)
                if i in cur:
                    cur = cur[i]
                    continue
            if isinstance(seg, int):
                s = str(seg)
                if s in cur:
                    cur = cur[s]
                    continue
            return default

        # list (strict index)
        if isinstance(cur, list):
            if isinstance(seg, int) or (isinstance(seg, str) and _is_int_str(seg)):
                idx = seg if isinstance(seg, int) else int(seg)
                if -len(cur) <= idx < len(cur):
                    cur = cur[idx]
                    continue
            return default

        # namedtuple (field or index)
        if isinstance(cur, tuple) and hasattr(cur, "_fields"):
            if isinstance(seg, str) and seg in getattr(cur, "_fields", ()):
                cur = getattr(cur, seg)
                continue
            if isinstance(seg, int) or (isinstance(seg, str) and _is_int_str(seg)):
                idx = seg if isinstance(seg, int) else int(seg)
                if -len(cur) <= idx < len(cur):
                    cur = cur[idx]
                    continue
            return default

        # generic non-string sequence (e.g., range)
        if isinstance(cur, AbcSequence) and not isinstance(cur, (str, bytes, bytearray)):
            if isinstance(seg, int) or (isinstance(seg, str) and _is_int_str(seg)):
                idx = seg if isinstance(seg, int) else int(seg)
                L = len(cur)
                if -L <= idx < L:
                    cur = cur[idx]
                    continue
            return default

        # object attribute (never return callables)
        attr = getattr(cur, str(seg), _MISSING)
        if attr is _MISSING or callable(attr):
            return default
        cur = attr

    return cur

clone_with()

Creates a shallow clone of obj with a customizer. The customizer may take: (value, key, parent) or (value, key) or (value)

Implementation

Args: obj: Object to clone. customizer: Customizer function.

Returns:
    Cloned object.

Example

obj = {"a": 1, "b": 2}
cloned = _.clone_with(obj, lambda x: x + 1)
cloned

Expected output: {'a': 2, 'b': 3}

Source Code

def clone_with(obj: Any, customizer: Callable[..., Any]) -> Any:
    def _call(v, k=None, p=None):
        try:
            return customizer(v, k, p)
        except TypeError:
            try:
                return customizer(v, k)
            except TypeError:
                return customizer(v)

    if isinstance(obj, dict):
        out = {}
        for k, v in obj.items():
            nv = _call(v, k, obj)
            out[k] = v if nv is None else nv
        return out
    if isinstance(obj, list):
        out = []
        for i, v in enumerate(obj):
            nv = _call(v, i, obj)
            out.append(v if nv is None else nv)
        return out
    # non-container: customizer can override value, else return as-is
    nv = _call(obj)
    return obj if nv is None else nv

apply_if_not_none()

Applies a function to some arguments if none of the arguments are None. Otherwise, return None.

Implementation

Args: fn: The function to apply. args: The positional arguments to apply the function to. *kwargs: The keyword arguments to apply the function with.

Returns:
    The result of applying the function to the arguments, or None if any of the arguments are None.

Example

apply_if_not_none(lambda x, y: x + y, 1, 2)

Expected output: 3

Source Code

def apply_if_not_none(fn: Callable[..., U], *args: Any, **kwargs: Any) -> Optional[U]:
    real_fn, a, kw = _split_apply_args(fn, *args, **kwargs)
    if all(arg is not None for arg in a):
        return real_fn(*a, **kw)
    return None

apply()

Applies a function to some arguments. Supports functions with variable arity, functions with keyword arguments, and functions with default arguments.

Implementation

Args: fn: The function to apply. args: The positional arguments to apply the function to. *kwargs: The keyword arguments to apply the function with.

Returns:
    The result of applying the function to the arguments.

Example

apply(lambda x, y: x + y, 1, 2)

Expected output: 3

Source Code

def apply(fn: Callable[..., U], *args: Any, **kwargs: Any) -> U:
    real_fn, a, kw = _split_apply_args(fn, *args, **kwargs)
    return real_fn(*a, **kw)

map_values_deep()

Map all non-object values in obj with return values from fn. The iteratee is invoked with two arguments: (obj_value, property_path) where property_path contains the list of path keys corresponding to the path of obj_value.

Implementation

Args: obj: Object to map. fn: Iteratee applied to each value.

Returns:
    The modified object.

Warning:
    `obj` is modified in place.

Example

x = {"a": 1, "b": {"c": 2}}
y = map_values_deep(x, lambda val: val * 2)
y == {"a": 2, "b": {"c": 4}}

Expected output: True

Source Code

def map_values_deep(obj: Any, fn: Callable[..., Any]) -> Any:
    def _walk(x: Any, path: List[Union[str, int]]) -> Any:
        if isinstance(x, dict):
            return {k: _walk(v, path + [k]) for k, v in x.items()}
        if isinstance(x, list):
            return [_walk(v, path + [i]) for i, v in enumerate(x)]
        try:
            return fn(x, path)          # (value, property_path)
        except TypeError:
            return fn(x)                # (value) fallback
    return _walk(obj, [])

find_key()

Finds the first key of a dictionary or list that satisfies the predicate.

Implementation

Args: obj: The dictionary or list to search. predicate: An optional function that returns True for elements to include. If not provided, the truthiness of the element itself is used.

Returns:
    The first key that satisfies the predicate, or None if not found.

Example

find_key({"a": 1, "b": 2, "c": 3}, lambda x: x > 1)

Expected output: 'b'

Source Code

def find_key(obj, predicate=None):
    pred = predicate or (lambda v: bool(v))
    for k, v in _iter_items_like(obj):
        if pred(v):
            return k
    return None

assign_with()

Assigns properties of source object(s) to the destination object.

Implementation

Args: target: Destination object whose properties will be modified. sources: Source objects to assign to target. customizer: Customizer applied per iteration.

Returns:
    Modified `target`.

Warning:
    `target` is modified in place.

Example

target = {"a": 1}
assign_with(target, {"b": 2}, lambda o, s, k, t: s if o is None else o)

Expected output: {'a': 1, 'b': 2}

Source Code

def assign_with(target: dict, *sources, customizer=None) -> dict:
    if customizer is None and sources and callable(sources[-1]):
        *sources, customizer = sources
    if customizer is None or not callable(customizer):
        raise TypeError("assign_with() missing 1 required argument: 'customizer'")

    for src in sources:
        if not isinstance(src, dict):
            try:
                src = dict(src)
            except Exception:
                continue
        for k, v in src.items():
            obj_val = target.get(k, None)
            # flexible-arity customizer: (obj_val, src_val, key, target) → fewer args if needed
            try:
                newv = customizer(obj_val, v, k, target)
            except TypeError:
                try:
                    newv = customizer(obj_val, v, k)
                except TypeError:
                    try:
                        newv = customizer(obj_val, v)
                    except TypeError:
                        newv = customizer(v)
            target[k] = v if newv is None else newv
    return target

omit_by()

Omit properties from an object using a predicate.

Implementation

Args: obj: The object to omit properties from. predicate: A predicate function that takes two arguments (value, key) and returns True if the property should be omitted or False if it should be kept.

Returns:
    A new object with omitted properties.

Example

omit_by({"a": 1, "b": 2, "c": 3}, lambda v, k: k.startswith("b")) == {"a": 1, "c": 3}

Expected output: True

Source Code

def omit_by(obj, predicate=None):
    if predicate is None:
        return to_dict(obj)
    if isinstance(predicate, (list, tuple, set)):
        return {k: v for k, v in to_dict(obj).items() if k not in predicate}
    return {k: v for k, v in _iter_items_like(obj) if not predicate(v, k)}

omit()

Omit properties from an object.

Implementation

Args: obj: The object to omit properties from. *keys_to_omit: Property names to omit.

Returns:
    A new object with omitted properties.

Example

omit({"a": 1, "b": 2, "c": 3}, "b", "c") == {"a": 1}

Expected output: True

Source Code

def omit(obj, *keys_to_omit):
    keys_flat = _flatten_keys(keys_to_omit)
    if isinstance(obj, (list, tuple)):
        base = to_dict(obj)
        return {k: v for k, v in base.items() if k not in keys_flat}
    base = dict(_iter_items_like(obj)) if not isinstance(obj, dict) else obj
    # deep path omit (e.g., "a.b[0].c")
    simple_keys = [
        k
        for k in keys_flat
        if not isinstance(k, str) or ("." not in k and "[" not in k)
    ]
    out = {k: v for k, v in base.items() if k not in simple_keys}
    # handle deep string paths
    for p in keys_flat:
        if isinstance(p, str) and (("." in p) or ("[" in p)):
            unset(out, p)
    return out

merge()

Deep merge dictionaries. Special cases: - If called with a single list, returns a deep clone of the list. - If called with a single None, returns None. - Lists under the same key are merged element-wise (no appending new items unless one side is longer); dict elements at the same index are merged recursively; non-dict/list elements prefer the right side. Args: objects: Objects to merge.

Implementation

Returns: Merged object.

Warning:
    Objects are modified in place.  If you need a copy, use :func:`clone_deep`.

Example

obj = {"a": 1}
obj2 = merge(obj, {"b": 2}, {"c": 3}, {"a": 4})
obj is obj2

Expected output: True

Source Code

def merge(*objects: Any) -> Any:
    if not objects:
        return {}

    head = objects[0]

    # Pass-through semantics for single arg cases
    if len(objects) == 1 and (head is None or isinstance(head, list)):
        return clone_deep(head) if isinstance(head, list) else head
    if head is None:
        return None

    def _merge_two(a: Any, b: Any) -> Any:
        # If either isn’t a dict, prefer b unless b is None
        if not isinstance(a, dict) or not isinstance(b, dict):
            if isinstance(a, (dict, list)) and b is None:
                return clone_deep(a)
            if isinstance(b, (dict, list)):
                return clone_deep(b)
            return b if b is not None else a

        # Both dicts: start with a (cloned where needed), then fold in b
        res: Dict[Any, Any] = {
            k: clone_deep(v) if isinstance(v, (dict, list)) else v
            for k, v in a.items()
        }

        for k, v in b.items():
            if k in res:
                av = res[k]
                if isinstance(av, dict) and isinstance(v, dict):
                    res[k] = _merge_two(av, v)
                elif isinstance(av, list) and isinstance(v, list):
                    # Element-wise merge for lists (no blind append)
                    m = max(len(av), len(v))
                    out: List[Any] = []
                    for i in range(m):
                        if i < len(av) and i < len(v) and isinstance(av[i], dict) and isinstance(v[i], dict):
                            out.append(_merge_two(av[i], v[i]))
                        elif i < len(av) and i < len(v):
                            out.append(clone_deep(v[i]))
                        elif i < len(av):
                            out.append(clone_deep(av[i]))
                        else:
                            out.append(clone_deep(v[i]))
                    res[k] = out
                else:
                    res[k] = clone_deep(v) if isinstance(v, (dict, list)) else v
            else:
                res[k] = clone_deep(v) if isinstance(v, (dict, list)) else v

        return res

    result: Any = head if isinstance(head, dict) else {}
    # If head is a dict, fold remaining dicts into it; otherwise just fold all dicts
    for o in (objects[1:] if isinstance(head, dict) else objects):
        if isinstance(o, dict):
            result = _merge_two(result, o) if result else clone_deep(o)
        elif result == {} and o in (None, [], {}):
            # ignore empty-ish inputs
            continue

    return result

defaults_deep()

Assigns properties of source object(s) to the destination object for all destination properties that resolve to undefined. This method is like :func:defaults except that it recursively assigns default properties.

Implementation

Args: target: Destination object whose properties will be modified. sources: Source objects to assign to target.

Returns:
    Modified `target`.

Warning:
    `target` is modified in place.

Example

obj = {"a": 1}
obj2 = defaults_deep(obj, {"b": 2}, {"c": 3}, {"a": 4})
obj is obj2

Expected output: True

Source Code

def defaults_deep(target: Dict[Any, Any], *sources: Dict[Any, Any]) -> Dict[Any, Any]:
    def _dd(a, b):
        # both dicts
        if isinstance(a, dict) and isinstance(b, dict):
            for k, v in b.items():
                if k in a:
                    a[k] = _dd(a[k], v)
                else:
                    a[k] = clone_deep(v) if isinstance(v, (dict, list)) else v
            return a
        # element-wise lists-of-dicts merge (no append)
        if isinstance(a, list) and isinstance(b, list):
            m = min(len(a), len(b))
            for i in range(m):
                if isinstance(a[i], dict) and isinstance(b[i], dict):
                    a[i] = _dd(a[i], b[i])
            return a
        # if a already set, keep it
        return (
            a if a is not None else clone_deep(b) if isinstance(b, (dict, list)) else b
        )

    for src in sources:
        if isinstance(src, dict):
            target = _dd(target, src) # type: ignore
    return target

clone_deep_with()

Creates a deep clone of obj with a customizer. The customizer may take: (value, key, parent) or (value, key) or (value)

Implementation

Args: obj: Object to clone. customizer: Customizer function.

Returns:
    Cloned object.

Example

obj = {"a": 1, "b": 2}
cloned = _.clone_deep_with(obj, lambda x: x + 1)
cloned

Expected output: {'a': 2, 'b': 3}

Source Code

def clone_deep_with(obj: Any, customizer: Callable) -> Any:
    def _clone(x, key=None, parent=None):
        customized = _call_customizer(customizer, x, key, parent)
        if customized is not None:
            return customized
        if isinstance(x, dict):
            return {k: _clone(v, k, x) for k, v in x.items()}
        if isinstance(x, list):
            return [_clone(v, i, x) for i, v in enumerate(x)]
        return x

    return _clone(obj)

clone_deep()

Creates a deep copy of an object.

Implementation

This function will not clone functions, methods, or modules.

Example

obj = {"a": 1, "b": 2}
cloned = _.clone_deep(obj)
cloned

Expected output: {'a': 1, 'b': 2}

Source Code

def clone_deep(obj: Any) -> Any:
    memo: Dict[int, Any] = {}
    stack: list[tuple[Any, Any | None, Any | None]] = [(obj, None, None)]
    root: Any = None

    while stack:
        src, parent, key = stack.pop()
        sid = id(src)
        if sid in memo:
            val = memo[sid]
        elif isinstance(src, dict):
            val = {}
            memo[sid] = val
            # push children
            for k, v in src.items():
                stack.append((v, val, k))
        elif isinstance(src, list):
            val = []
            memo[sid] = val
            for i, v in enumerate(src):
                stack.append((v, val, i))
        else:
            # immutable or custom object
            try:
                val = src.__class__(src) if hasattr(src, "__iter__") and not isinstance(src, (str, bytes, bytearray)) else src
            except Exception:
                val = src
            memo[sid] = val

        if parent is None:
            root = val
        else:
            if isinstance(parent, list) and isinstance(key, int):
                _ensure_len(parent, key + 1)
                parent[key] = val
            else:
                parent[key] = val # type: ignore

    return root

for_in_right()

Iterate over an object (dict or sequence) in reverse order, calling iteratee for each element.

Implementation

Args: obj: The object to iterate over. iteratee: A function of three arguments: (value, key, obj). Return False to break the loop.

Returns:
    The original `obj`.

Example

obj = {"a": 1, "b": 2}
for_in_right(obj, lambda v, k, o: print(f"{k}: {v}"))

Expected output: b: 2 a: 1

Source Code

def for_in_right(obj, iteratee):
    pairs = list(_iter_items_like(obj))
    for k, v in reversed(pairs):
        res = iteratee(v, k, obj)
        if res is False:
            break
    return obj

for_in()

Iterate over an object (dict or sequence), calling iteratee for each element.

Implementation

Args: obj: The object to iterate over. iteratee: A function of three arguments: (value, key, obj). Return False to break the loop.

Returns:
    The original `obj`.

Example

obj = {"a": 1, "b": 2}
for_in(obj, lambda v, k, o: print(f"{k}: {v}"))

Expected output: a: 1 b: 2

Source Code

def for_in(obj, iteratee):
    for k, v in _iter_items_like(obj):
        res = iteratee(v, k, obj)
        if res is False:
            break
    return obj

find_last_key()

Finds the last key of a dictionary or list that satisfies the predicate.

Implementation

Args: obj: The dictionary or list to search. predicate: An optional function that returns True for elements to include. If not provided, the truthiness of the element itself is used.

Returns:
    The last key that satisfies the predicate, or None if not found.

Example

find_last_key({'a': 1, 'b': 2, 'c': 3}, lambda x: x > 1)

Expected output: 'c'

Source Code

def find_last_key(obj, predicate=None):
    pairs = list(_iter_items_like(obj))
    pred = predicate or (lambda _: True)
    for k, v in reversed(pairs):
        if pred(v):
            return k
    return None

update()

Update value at path by applying updater (or using it as a constant).

Implementation

Args: obj: The object to modify. path: The path of the property to update. updater: Function that returns updated value.

Returns:
    Updated `obj`.

Warning:
    `obj` is modified in place.

Example

obj = {"a": [{"b": {"c": 7}}]}
update(obj, "a[0].b.c", lambda x: x**2)

Expected output: {'a': [{'b': {'c': 49}}]}

Source Code

def update(obj, path, updater):
    current = get(obj, path, None)
    newval = updater(current)
    set_(obj, path, newval)
    return obj

extend()

Extends an object with properties from other objects

Implementation

Uses dict.update() to merge dictionaries

Example

extended = UniCoreFW.extend({"name": "John"}, {"age": 30}, {"city": "New York"})

Expected output: {"name": "John", "age": 30, "city": "New York"}

Source Code

def extend(obj, *sources):
    for source in sources:
        obj.update(source)
    return obj

iterator()

Yield (key, value) pairs from mappings, sequences, or objects that expose items/iteritems/attributes.

Implementation

Args: obj: The object to iterate

Returns:
    A generator that yields (key, value) pairs

Example

list(iterator({"a": 1, "b": 2}))

Expected output: [("a", 1), ("b", 2)]

Source Code

def iterator(obj):
    return _iter_items_like(obj)

has()

Checks if an object has a property

Implementation

Uses the 'in' operator for key lookup

Example

has_name = UniCoreFW.has({"name": "John"}, "name")

Expected output: True

Source Code

def has(obj, key):
    return key in obj

object()

Creates an object from keys and values arrays

Implementation

Uses dict comprehension with zip-like pairing

Example

obj = UniCoreFW.object(["name", "age"], ["John", 30])

Expected output: {"name": "John", "age": 30}

Source Code

def object(keys, values):
    if len(keys) != len(values):
        raise ValueError("Keys and values must have the same length")
    return {keys[i]: values[i] for i in range(len(keys))}

pairs()

Converts an object to key-value pairs

Implementation

Wraps dict.items() with list conversion

Example

pairs = UniCoreFW.pairs({"name": "John", "age": 30})

Expected output: [("name", "John"), ("age", 30)]

Source Code

def pairs(obj):
    return list(obj.items())

where()

Finds objects matching criteria

Implementation

Uses list comprehension with predicate for matching all criteria

Example

active_users = UniCoreFW.where([{"name": "John", "active": True}, {"name": "Jane", "active": True}, {"name": "Bob", "active": False}], {"active": True})

Expected output: [{"name": "John", "active": True}, {"name": "Jane", "active": True}]

Source Code

def where(obj_list, properties):
    return [
        obj
        for obj in obj_list
        if all(obj.get(k) == v for k, v in properties.items())
    ]

defaults()

Sets default values for missing properties

Implementation

Copies the object and adds missing properties from defaults

Example

with_defaults = UniCoreFW.defaults({"name": "John"}, {"age": 30, "city": "Unknown"})

Expected output: {"name": "John", "age": 30, "city": "Unknown"}

Source Code

def defaults(obj, *defaults):
    if not isinstance(obj, dict):
        raise TypeError("The 'obj' parameter must be a dictionary.")

    # Create a copy to avoid modifying the original object
    result = obj.copy()

    for default in defaults:
        if not isinstance(default, dict):
            raise TypeError("Each default must be a dictionary.")
        for key, value in default.items():
            if key not in obj:
                obj[key] = value
            if not isinstance(key, str):
                raise ValueError("Keys in defaults must be strings.")
            # Only set the default if the key is not already in 'result'
            if key not in result:
                result[key] = value
    return result

invert()

Inverts an object's keys and values

Implementation

Uses dict comprehension to swap keys and values

Example

inverted = UniCoreFW.invert({"name": "John", "age": 30})

Expected output: {"John": "name", 30: "age"}

Source Code

def invert(obj):
    return {v: k for k, v in obj.items()}

unset()

Removes the property at path of obj.

Implementation

Args: obj: The object to modify. path: The path of the property to unset.

Returns:
    Whether the property was deleted.

Warning:
    `obj` is modified in place.

Example

obj = {"a": [{"b": {"c": 7}}]}
unset(obj, "a[0].b.c")

Expected output: True

Source Code

def unset(obj, path) -> bool:
    parts = _as_parts_any(path)
    if not parts:
        return False

    cur = obj
    for part in parts[:-1]:
        if isinstance(cur, dict):
            if part not in cur:
                return False
            cur = cur[part]
        elif isinstance(cur, list) and isinstance(part, int):
            if part < 0 or part >= len(cur):
                return False
            cur = cur[part]
        else:
            if not hasattr(cur, str(part)):
                return False
            cur = getattr(cur, str(part))

    last = parts[-1]

    if isinstance(cur, dict):
        val = cur.pop(last, _MISSING)
        return val is not _MISSING

    if isinstance(cur, list) and isinstance(last, int):
        if 0 <= last < len(cur):
            # list.pop accepts only the index (no default)
            cur.pop(last)
            return True
        return False

    if hasattr(cur, str(last)):
        try:
            delattr(cur, str(last))
            return True
        except Exception:
            return False

    return False

invert_by()

Invert a dictionary or list/tuple, or make a best effort at doing so on any items-like object, with an optional iteratee to transform the values to be used as keys in the inverted object.

Implementation

Args: obj: The dictionary, list, tuple, or other object to invert iteratee: An optional callable that takes a value and returns a key value to use in the inverted object. If not provided, the values will be used as-is.

Returns:
    A dictionary with the transformed values as keys, and lists of the
    original keys as values.

Example

invert_by({"a": 1, "b": 2}, lambda x: x * 2)

Expected output: {2: ["a"], 4: ["b"]}

Source Code

def invert_by(obj, iteratee=None):
    fn = iteratee or (lambda x: x)
    out: Dict[Any, List[Any]] = {}
    for k, v in _iter_items_like(obj):
        key_val = fn(v)
        out.setdefault(key_val, []).append(k)
    return out

callables()

Return a list of the keys of all callable values in obj.

Implementation

Args: obj: The object to search

Returns:
    A list of keys of callable values

Example

callables({"a": 1, "b": lambda x: x})

Expected output: ["b"]

Source Code

def callables(obj) -> list:
    return [k for k, v in _iter_items_like(obj) if callable(v)]

create()

Creates an object that inherits from a prototype

Implementation

Creates a new dictionary class that initializes with the prototype

Example

proto_obj = UniCoreFW.create({"type": "person"})

Expected output: Dictionary with 'type': 'person' pre-populated

Source Code

def create(proto):
    if not isinstance(proto, dict):
        raise TypeError("Prototype must be a dictionary")

    class Obj(dict):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.update(proto)

    return Obj()

result()

Gets a property value or calls it if it's a function

Implementation

Checks if the property is callable and invokes it if needed

Example

value = UniCoreFW.result({"name": "John", "getAge": lambda: 30}, "getAge")

Expected output: 30

Source Code

def result(obj, property_name, *args):
    value = obj.get(property_name)

    if callable(value):
        # Directly call the function with args if it's callable
        return value(*args)

    return value

size()

Returns the number of values in an object

Implementation

Uses len() or iterator counting depending on the type

Example

size = UniCoreFW.size({"name": "John", "age": 30})

Expected output: 2

Source Code

def size(obj):
    if hasattr(obj, "__len__"):
        return len(obj)
    return sum(1 for _ in obj)

to_array()

Converts an object into an array

Implementation

Handles different types with appropriate conversion methods

Example

arr = UniCoreFW.to_array({"name": "John", "age": 30})

Expected output: ["John", 30]

Source Code

def to_array(obj):
    if isinstance(obj, list):
        return obj
    elif isinstance(obj, (dict, set)):
        return list(obj.values()) if isinstance(obj, dict) else list(obj)
    elif hasattr(obj, "__iter__"):
        return list(obj)
    return [obj]

map_object()

Maps object values using a function

Implementation

Uses dict comprehension to transform values

Example

mapped = UniCoreFW.map_object({"a": 1, "b": 2}, lambda x: x * 2)

Expected output: {"a": 2, "b": 4}

Source Code

def map_object(obj, func):
    return {k: func(v) for k, v in obj.items()}

functions()

Gets names of functions in an object

Implementation

Filters keys based on callable values

Example

funcs = UniCoreFW.functions({"name": "John", "greet": lambda: "Hello"})

Expected output: ["greet"]

Source Code

def functions(obj):
    if not isinstance(obj, dict):
        raise TypeError("Input must be a dictionary.")

    return [
        key
        for key, value in obj.items()
        if callable(value) and not key.startswith("__")
    ]

all_keys()

Gets all keys of an object

Implementation

Returns all keys including inherited ones

Example

all_keys = UniCoreFW.all_keys({"name": "John", "age": 30})

Expected output: ["name", "age"]

Source Code

def all_keys(obj):
    if isinstance(obj, dict):
        return list(obj.keys())
    else:
        raise TypeError("The input must be a dictionary.")

is_match()

Checks if an object matches attributes

Implementation

Verifies all key-value pairs match specified attributes

Example

is_match = UniCoreFW.is_match({"name": "John", "age": 30}, {"name": "John"})

Expected output: True

Source Code

def is_match(obj, attrs):
    return all(obj.get(k) == v for k, v in attrs.items())