ExplicitEnum subclass str (JSON dump compatible) (#17933)

* ExplicitEnum subclass str (JSON dump compatible)

* allow union if one of the types is str
This commit is contained in:
Bram Vanroy 2022-06-29 19:49:31 +02:00 committed by GitHub
parent b089cca347
commit bc019b0e5f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 4 additions and 2 deletions

View File

@ -84,7 +84,9 @@ class HfArgumentParser(ArgumentParser):
origin_type = getattr(field.type, "__origin__", field.type)
if origin_type is Union:
if len(field.type.__args__) != 2 or type(None) not in field.type.__args__:
if str not in field.type.__args__ and (
len(field.type.__args__) != 2 or type(None) not in field.type.__args__
):
raise ValueError(
"Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because"
" the argument parser only supports one type per argument."

View File

@ -240,7 +240,7 @@ class ModelOutput(OrderedDict):
return tuple(self[k] for k in self.keys())
class ExplicitEnum(Enum):
class ExplicitEnum(str, Enum):
"""
Enum with more explicit error message for missing values.
"""