Skip to content

Commit 923468b

Browse files
committed
optional import
1 parent fe3e4ba commit 923468b

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

src/jobflow/utils/uid.py

+20-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,23 @@
33

44
from uuid import UUID
55

6-
import ulid
6+
try: # pragma: no cover
7+
from ulid import ULID
8+
except ImportError: # pragma: no cover
9+
err_msg = (
10+
"The ulid package is not installed. "
11+
"Install it with `pip install jobflow[ulid]` or `pip install python-ulid`."
12+
)
13+
14+
class ULID: # type: ignore
15+
"""Fake ULID class for raising import error."""
16+
17+
def __init__(self, *args, **kwargs):
18+
raise ImportError(err_msg)
19+
20+
def from_str(self, *args, **kwargs):
21+
"""Raise import error."""
22+
raise ImportError(err_msg)
723

824

925
def suid(id_type: str | None = None) -> str:
@@ -33,7 +49,7 @@ def suid(id_type: str | None = None) -> str:
3349
funcs = {
3450
"uuid1": uuid.uuid1,
3551
"uuid4": uuid.uuid4,
36-
"ulid": ulid.ULID,
52+
"ulid": ULID,
3753
}
3854
if id_type not in funcs:
3955
raise ValueError(f"UUID type {id_type} not supported.")
@@ -61,7 +77,7 @@ def get_timestamp_from_uid(uid: str) -> float:
6177
)
6278
funcs = {
6379
"uuid1": lambda uuid: (UUID(uuid).time - 0x01B21DD213814000) / 1e7,
64-
"ulid": lambda uuid: ulid.ULID.from_str(uuid).timestamp,
80+
"ulid": lambda uuid: ULID.from_str(uuid).timestamp,
6581
}
6682
return funcs[id_type](uid)
6783

@@ -90,7 +106,7 @@ def _get_id_type(uid: str) -> str:
90106
pass
91107

92108
try:
93-
ulid.ULID.from_str(uid)
109+
ULID.from_str(uid)
94110
return "ulid"
95111
except ValueError:
96112
pass

0 commit comments

Comments
 (0)