Skip to content

Commit d13c475

Browse files
committed
make clean_str_attr function more robust
1 parent 56144bc commit d13c475

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

src/pynxtools/dataconverter/helpers.py

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1191,17 +1191,28 @@ def nested_dict_to_slash_separated_path(
11911191

11921192

11931193
def clean_str_attr(
1194-
attr: Optional[Union[str, bytes]], encoding="utf-8"
1194+
attr: Optional[Union[str, bytes]], encoding: str = "utf-8"
11951195
) -> Optional[str]:
11961196
"""
1197-
Cleans the string attribute which means it will decode bytes to str if necessary.
1198-
If `attr` is not str, bytes or None it raises a TypeError.
1197+
Return the attribute as a string.
1198+
1199+
- If `attr` is `bytes`, decode it using the given encoding.
1200+
- If `attr` is already a string, return it unchanged.
1201+
- If `attr` is `None`, return `None`.
1202+
- Otherwise, raise TypeError.
1203+
1204+
Args:
1205+
attr: A string, bytes, or None.
1206+
encoding: The character encoding to use when decoding bytes.
1207+
1208+
Returns:
1209+
The attribute as a string, or None if input was None.
1210+
1211+
Raises:
1212+
TypeError: If `attr` is not str, bytes, or None.
11991213
"""
1200-
if attr is None:
1214+
if attr is None or isinstance(attr, str):
12011215
return attr
12021216
if isinstance(attr, bytes):
12031217
return attr.decode(encoding)
1204-
if isinstance(attr, str):
1205-
return attr
1206-
1207-
return attr
1218+
raise TypeError(f"Expected str, bytes, or None; got {type(attr).__name__}")

0 commit comments

Comments
 (0)