Replies: 3 comments
-
I am not sure what is the neat/correct way of solving it, SO has all sort of answers (https://stackoverflow.com/questions/41407414/convert-string-to-enum-in-python) this stands out as a neat one: https://stackoverflow.com/a/56567247 |
Beta Was this translation helpful? Give feedback.
-
from enum import Enum
class YetAnotherStrEnum(Enum):
@classmethod
def from_str(cls, s: str):
return cls.__members__.get(s)
@classmethod
def from_enum_or_str(cls, s_or_e):
if isinstance(s_or_e, str):
return cls.from_str(s_or_e)
else:
return s_or_e
class ExportFormat(YetAnotherStrEnum):
"""This specifies the format of the file to be imported. By default, this is `SOURCE`. However it
may be one of: `SOURCE`, `HTML`, `JUPYTER`, `DBC`. The value is case sensitive."""
DBC = 'DBC'
HTML = 'HTML'
JUPYTER = 'JUPYTER'
R_MARKDOWN = 'R_MARKDOWN'
SOURCE = 'SOURCE'
aaa = 'bbb'
assert ExportFormat.from_str('SOURCE') == ExportFormat.SOURCE
assert ExportFormat.from_enum_or_str('SOURCE') == ExportFormat.SOURCE
assert ExportFormat.from_enum_or_str(ExportFormat.SOURCE) == ExportFormat.SOURCE hence calling code can be change from: if format: query['format'] = request.format.value to: if format: query['format'] = ExportFormat.from_enum_or_str(request.format).value this way both |
Beta Was this translation helpful? Give feedback.
-
Another issue...with displaying/repr for classes having enums, displayed text has nasty looking ObjectInfo(created_at=1677658169185, language=<Language.SQL: 'SQL'>, modified_at=1677658409090, object_id=3538949529947478, object_type=<ObjectType.NOTEBOOK: 'NOTEBOOK'>, path='/Users/grzegorz.rusin@databricks.com/auto-dlt/generated/gr_products/gr_silver-incremental', size=None)] displayed text should look like this, so it can be copied and run to created object back: from databricks.sdk.service.workspace import ObjectType, Language, ObjectInfo
ObjectInfo(created_at=1677658169185, language=Language.SQL, modified_at=1677658409090, object_id=3538949529947478, object_type=ObjectType.NOTEBOOK, path='/Users/grzegorz.rusin@databricks.com/auto-dlt/generated/gr_products/gr_silver-incremental', size=None) Solution:adding custom string formatter: class YetAnotherStrEnum(Enum):
...
def __repr__(self):
return str(self) gets rid of nasty EnumType.FieldName: FieldValue formatting, in favour of just EnumType.FieldName |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Problem
Generated Enum types does not have support of being instantiated from string, hence it forces end users to not use non pythonic syntax of:
instead of neat, short, and pythonic:
throws an exception:
Example
For example:
has signature of:
in turn parameter
format
is of Enum type defined indatabricks.sdk.service.workspace.ExportFormat
asBeta Was this translation helpful? Give feedback.
All reactions