|
11 | 11 | from .utils import add_exc_note, fspaths_converter, is_union |
12 | 12 |
|
13 | 13 | LIST_MIME = "+list-of" |
| 14 | +TUPLE_MIME = "+tuple-of" |
14 | 15 | IANA_MIME_TYPE_REGISTRIES = [ |
15 | 16 | "application", |
16 | 17 | "audio", |
@@ -101,13 +102,18 @@ def from_mime( |
101 | 102 | FormatRecognitionError |
102 | 103 | if the MIME string does not correspond to a valid file format class |
103 | 104 | """ |
104 | | - if mime_str.endswith(LIST_MIME): |
105 | | - item_mime = mime_str[: -len(LIST_MIME)] |
| 105 | + if match := re.match( |
| 106 | + r".*(" + re.escape(LIST_MIME) + "|" + re.escape(TUPLE_MIME) + r")$", mime_str |
| 107 | + ): |
| 108 | + item_mime = mime_str[: -len(match.group(1))] |
106 | 109 | if item_mime.startswith("[") and item_mime.endswith("]"): |
107 | 110 | item_mime = item_mime[1:-1] |
108 | | - return ty.List[from_mime(item_mime)] # type: ignore |
109 | | - if "," in mime_str: |
110 | | - return functools.reduce(operator.or_, (from_mime(t) for t in mime_str.split(","))) # type: ignore |
| 111 | + if match.group(1) == LIST_MIME: |
| 112 | + return list[from_mime(item_mime)] # type: ignore |
| 113 | + else: |
| 114 | + return tuple[from_mime(item_mime)] # type: ignore |
| 115 | + if "|" in mime_str: |
| 116 | + return functools.reduce(operator.or_, (from_mime(t) for t in mime_str.split("|"))) # type: ignore |
111 | 117 | return fileformats.core.DataType.from_mime(mime_str) |
112 | 118 |
|
113 | 119 |
|
@@ -149,14 +155,14 @@ def to_mime( |
149 | 155 | f"Cannot convert {datatype} to official mime-type as it is not a proper " |
150 | 156 | 'file-type, please use official=False to convert to "mime-like" string instead' |
151 | 157 | ) |
152 | | - if origin is list: |
| 158 | + if origin in (list, tuple): |
153 | 159 | item_mime = to_mime(ty.get_args(datatype)[0], official=official) |
154 | 160 | if "," in item_mime: |
155 | 161 | item_mime = "[" + item_mime + "]" |
156 | | - item_mime += LIST_MIME |
| 162 | + item_mime += LIST_MIME if origin is list else TUPLE_MIME |
157 | 163 | return item_mime |
158 | 164 | if is_union(datatype): |
159 | | - return ",".join(to_mime(t, official=official) for t in ty.get_args(datatype)) |
| 165 | + return "|".join(to_mime(t, official=official) for t in ty.get_args(datatype)) |
160 | 166 | if ( |
161 | 167 | isinstance(datatype, str) |
162 | 168 | and datatype.startswith("fileformats.") |
|
0 commit comments