Skip to content

Commit

Permalink
optional import
Browse files Browse the repository at this point in the history
  • Loading branch information
jmmshn committed Jan 22, 2024
1 parent fe3e4ba commit 923468b
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions src/jobflow/utils/uid.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,23 @@

from uuid import UUID

import ulid
try: # pragma: no cover
from ulid import ULID
except ImportError: # pragma: no cover
err_msg = (

Check warning on line 9 in src/jobflow/utils/uid.py

View check run for this annotation

Codecov / codecov/patch

src/jobflow/utils/uid.py#L8-L9

Added lines #L8 - L9 were not covered by tests
"The ulid package is not installed. "
"Install it with `pip install jobflow[ulid]` or `pip install python-ulid`."
)

class ULID: # type: ignore

Check warning on line 14 in src/jobflow/utils/uid.py

View check run for this annotation

Codecov / codecov/patch

src/jobflow/utils/uid.py#L14

Added line #L14 was not covered by tests
"""Fake ULID class for raising import error."""

def __init__(self, *args, **kwargs):
raise ImportError(err_msg)

Check warning on line 18 in src/jobflow/utils/uid.py

View check run for this annotation

Codecov / codecov/patch

src/jobflow/utils/uid.py#L17-L18

Added lines #L17 - L18 were not covered by tests

def from_str(self, *args, **kwargs):

Check warning on line 20 in src/jobflow/utils/uid.py

View check run for this annotation

Codecov / codecov/patch

src/jobflow/utils/uid.py#L20

Added line #L20 was not covered by tests
"""Raise import error."""
raise ImportError(err_msg)

Check warning on line 22 in src/jobflow/utils/uid.py

View check run for this annotation

Codecov / codecov/patch

src/jobflow/utils/uid.py#L22

Added line #L22 was not covered by tests


def suid(id_type: str | None = None) -> str:
Expand Down Expand Up @@ -33,7 +49,7 @@ def suid(id_type: str | None = None) -> str:
funcs = {
"uuid1": uuid.uuid1,
"uuid4": uuid.uuid4,
"ulid": ulid.ULID,
"ulid": ULID,
}
if id_type not in funcs:
raise ValueError(f"UUID type {id_type} not supported.")
Expand Down Expand Up @@ -61,7 +77,7 @@ def get_timestamp_from_uid(uid: str) -> float:
)
funcs = {
"uuid1": lambda uuid: (UUID(uuid).time - 0x01B21DD213814000) / 1e7,
"ulid": lambda uuid: ulid.ULID.from_str(uuid).timestamp,
"ulid": lambda uuid: ULID.from_str(uuid).timestamp,
}
return funcs[id_type](uid)

Expand Down Expand Up @@ -90,7 +106,7 @@ def _get_id_type(uid: str) -> str:
pass

try:
ulid.ULID.from_str(uid)
ULID.from_str(uid)
return "ulid"
except ValueError:
pass
Expand Down

0 comments on commit 923468b

Please sign in to comment.