Convert an object to a string If ``exclusive`` is specified, search through `obj` and convert values that are in ``exclusive``. Note that when searching through dictionaries, only values are converted, not the keys. Parameters ---------- obj : Any Object (or va
(obj, exclusive: Iterable | None = None)
| 2000 | |
| 2001 | |
| 2002 | def stringify(obj, exclusive: Iterable | None = None): |
| 2003 | """Convert an object to a string |
| 2004 | |
| 2005 | If ``exclusive`` is specified, search through `obj` and convert |
| 2006 | values that are in ``exclusive``. |
| 2007 | |
| 2008 | Note that when searching through dictionaries, only values are |
| 2009 | converted, not the keys. |
| 2010 | |
| 2011 | Parameters |
| 2012 | ---------- |
| 2013 | obj : Any |
| 2014 | Object (or values within) to convert to string |
| 2015 | exclusive: Iterable, optional |
| 2016 | Set of values to search for when converting values to strings |
| 2017 | |
| 2018 | Returns |
| 2019 | ------- |
| 2020 | result : type(obj) |
| 2021 | Stringified copy of ``obj`` or ``obj`` itself if it is already a |
| 2022 | string or bytes. |
| 2023 | |
| 2024 | Examples |
| 2025 | -------- |
| 2026 | >>> stringify(b'x') |
| 2027 | b'x' |
| 2028 | >>> stringify('x') |
| 2029 | 'x' |
| 2030 | >>> stringify({('a',0):('a',0), ('a',1): ('a',1)}) |
| 2031 | "{('a', 0): ('a', 0), ('a', 1): ('a', 1)}" |
| 2032 | >>> stringify({('a',0):('a',0), ('a',1): ('a',1)}, exclusive={('a',0)}) |
| 2033 | {('a', 0): "('a', 0)", ('a', 1): ('a', 1)} |
| 2034 | """ |
| 2035 | |
| 2036 | typ = type(obj) |
| 2037 | if typ is str or typ is bytes: |
| 2038 | return obj |
| 2039 | elif exclusive is None: |
| 2040 | return str(obj) |
| 2041 | |
| 2042 | if typ is list: |
| 2043 | return [stringify(v, exclusive) for v in obj] |
| 2044 | if typ is dict: |
| 2045 | return {k: stringify(v, exclusive) for k, v in obj.items()} |
| 2046 | try: |
| 2047 | if obj in exclusive: |
| 2048 | return stringify(obj) |
| 2049 | except TypeError: # `obj` not hashable |
| 2050 | pass |
| 2051 | if typ is tuple: # If the tuple itself isn't a key, check its elements |
| 2052 | return tuple(stringify(v, exclusive) for v in obj) |
| 2053 | return obj |
| 2054 | |
| 2055 | |
| 2056 | class cached_property(functools.cached_property): |
searching dependent graphs…