Skip to content

Commit db6f144

Browse files
committed
CLN: Make bz2 import optional
1 parent 49851bb commit db6f144

File tree

2 files changed

+28
-12
lines changed

2 files changed

+28
-12
lines changed

pandas/compat/compressors.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,17 @@
44

55
from __future__ import annotations
66

7-
import bz2
87
from pickle import PickleBuffer
98

109
from pandas.compat._constants import PY310
1110

11+
try:
12+
import bz2
13+
14+
has_bz2 = True
15+
except ImportError:
16+
has_bz2 = False
17+
1218
try:
1319
import lzma
1420

@@ -41,17 +47,19 @@ def flatten_buffer(
4147
return memoryview(b).tobytes("A")
4248

4349

44-
class BZ2File(bz2.BZ2File):
45-
if not PY310:
50+
if has_bz2:
4651

47-
def write(self, b) -> int:
48-
# Workaround issue where `bz2.BZ2File` expects `len`
49-
# to return the number of bytes in `b` by converting
50-
# `b` into something that meets that constraint with
51-
# minimal copying.
52-
#
53-
# Note: This is fixed in Python 3.10.
54-
return super().write(flatten_buffer(b))
52+
class BZ2File(bz2.BZ2File):
53+
if not PY310:
54+
55+
def write(self, b) -> int:
56+
# Workaround issue where `bz2.BZ2File` expects `len`
57+
# to return the number of bytes in `b` by converting
58+
# `b` into something that meets that constraint with
59+
# minimal copying.
60+
#
61+
# Note: This is fixed in Python 3.10.
62+
return super().write(flatten_buffer(b))
5563

5664

5765
if has_lzma:

pandas/io/common.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,6 @@
5959
)
6060
from pandas.compat import get_lzma_file
6161
from pandas.compat._optional import import_optional_dependency
62-
from pandas.compat.compressors import BZ2File as _BZ2File
6362
from pandas.util._decorators import doc
6463
from pandas.util._exceptions import find_stack_level
6564

@@ -73,6 +72,11 @@
7372
from pandas.core.indexes.api import MultiIndex
7473
from pandas.core.shared_docs import _shared_docs
7574

75+
try:
76+
from pandas.compat.compressors import BZ2File as _BZ2File
77+
except ImportError:
78+
_BZ2File = None
79+
7680
_VALID_URLS = set(uses_relative + uses_netloc + uses_params)
7781
_VALID_URLS.discard("")
7882
_RFC_3986_PATTERN = re.compile(r"^[A-Za-z][A-Za-z0-9+\-+.]*://")
@@ -766,6 +770,10 @@ def get_handle(
766770
elif compression == "bz2":
767771
# Overload of "BZ2File" to handle pickle protocol 5
768772
# "Union[str, BaseBuffer]", "str", "Dict[str, Any]"
773+
if _BZ2File is None:
774+
raise ImportError(
775+
"bz2 compression requires the bz2 module to be installed"
776+
)
769777
handle = _BZ2File( # type: ignore[call-overload]
770778
handle,
771779
mode=ioargs.mode,

0 commit comments

Comments
 (0)