11
11
12
12
import os
13
13
import platform
14
+ from pickle import PickleBuffer
14
15
import sys
15
- from typing import TYPE_CHECKING
16
+
17
+ try :
18
+ import lzma
19
+ has_lzma = True
20
+ except ImportError :
21
+ has_lzma = False
16
22
17
23
from pandas ._typing import F
18
24
from pandas .compat .numpy import (
31
37
pa_version_under9p0 ,
32
38
)
33
39
34
- if TYPE_CHECKING :
35
- import lzma
36
-
37
40
PY39 = sys .version_info >= (3 , 9 )
38
41
PY310 = sys .version_info >= (3 , 10 )
39
42
PY311 = sys .version_info >= (3 , 11 )
40
43
PYPY = platform .python_implementation () == "PyPy"
41
44
IS64 = sys .maxsize > 2 ** 32
42
45
43
46
47
+ if has_lzma :
48
+ class _LZMAFile (lzma .LZMAFile ):
49
+ def write (self , b ) -> None :
50
+ if isinstance (b , PickleBuffer ):
51
+ # Workaround issue where `lzma.LZMAFile` expects `len`
52
+ # to return the number of bytes in `b` by converting
53
+ # `b` into something that meets that constraint with
54
+ # minimal copying.
55
+ try :
56
+ # coerce to 1-D `uint8` C-contiguous `memoryview` zero-copy
57
+ b = b .raw ()
58
+ except BufferError :
59
+ # perform in-memory copy if buffer is not contiguous
60
+ b = bytes (b )
61
+ return super (_LZMAFile , self ).write (b )
62
+
63
+
44
64
def set_function_name (f : F , name : str , cls ) -> F :
45
65
"""
46
66
Bind the name/qualname attributes of the function.
@@ -126,7 +146,7 @@ def is_ci_environment() -> bool:
126
146
return os .environ .get ("PANDAS_CI" , "0" ) == "1"
127
147
128
148
129
- def get_lzma_file () -> type [lzma . LZMAFile ]:
149
+ def get_lzma_file () -> type [_LZMAFile ]:
130
150
"""
131
151
Importing the `LZMAFile` class from the `lzma` module.
132
152
@@ -140,15 +160,13 @@ def get_lzma_file() -> type[lzma.LZMAFile]:
140
160
RuntimeError
141
161
If the `lzma` module was not imported correctly, or didn't exist.
142
162
"""
143
- try :
144
- import lzma
145
- except ImportError :
163
+ if not has_lzma :
146
164
raise RuntimeError (
147
165
"lzma module not available. "
148
166
"A Python re-install with the proper dependencies, "
149
167
"might be required to solve this issue."
150
168
)
151
- return lzma . LZMAFile
169
+ return _LZMAFile
152
170
153
171
154
172
__all__ = [
0 commit comments