2929from psm_utils .psm_list import PSMList
3030
3131try :
32- import cbor2
32+ import cbor2 # type: ignore[import]
33+
34+ _has_cbor2 = True
3335except ImportError :
34- raise ImportError (
35- "The cbor2 package is required to use the CBOR reader/writer. "
36- "Install it with: pip install cbor2"
37- )
36+ _has_cbor2 = False
3837
3938logger = logging .getLogger (__name__ )
4039
@@ -57,13 +56,18 @@ def __init__(self, filename: str | Path, *args, **kwargs):
5756
5857 """
5958 super ().__init__ (filename , * args , ** kwargs )
59+ if not _has_cbor2 :
60+ raise ImportError (
61+ "The cbor2 package is required to use the CBOR reader/writer. "
62+ "Install it with: pip install cbor2"
63+ )
6064
6165 def __iter__ (self ):
6266 """Iterate over file and return PSMs one-by-one."""
6367 with open (self .filename , "rb" ) as open_file :
6468 try :
65- data = cbor2 .load (open_file )
66- except cbor2 .CBORDecodeError as e :
69+ data = cbor2 .load (open_file ) # type: ignore[attr-defined]
70+ except cbor2 .CBORDecodeError as e : # type: ignore[attr-defined]
6771 raise PSMUtilsIOException (f"Could not decode CBOR file: { e } " ) from e
6872
6973 if not isinstance (data , list ):
@@ -122,6 +126,11 @@ def __init__(
122126
123127 """
124128 super ().__init__ (filename , * args , ** kwargs )
129+ if not _has_cbor2 :
130+ raise ImportError (
131+ "The cbor2 package is required to use the CBOR reader/writer. "
132+ "Install it with: pip install cbor2"
133+ )
125134 self ._psm_cache : list [dict [str , Any ]] = []
126135
127136 def __enter__ (self ) -> CBORWriter :
@@ -155,6 +164,6 @@ def _psm_to_entry(psm: PSM) -> dict:
155164 def _flush (self ):
156165 """Write the cached PSMs to the CBOR file."""
157166 with open (self .filename , "wb" ) as open_file :
158- cbor2 .dump (self ._psm_cache , open_file )
167+ cbor2 .dump (self ._psm_cache , open_file ) # type: ignore[attr-defined]
159168
160169 self ._psm_cache = []
0 commit comments