Skip to content

Commit c4192a9

Browse files
karlwaldmanclaude
andcommitted
fix: build the visualizer lazily so client construction never warns (#151)
OilPriceAPI.__init__ built PriceVisualizer eagerly, which imported matplotlib when present and emitted ImportWarning when absent, so `python -W error` could not construct a client. `viz` is now a property that builds on first access and returns None without matplotlib (unchanged contract for `if not client.viz`). Plotting methods still raise ImportError with guidance. Also removes root clutter: test_debug_params.py (an ad-hoc live-call debug script, not a test; pytest testpaths is tests/) and WEBSITE_FIXES_DEPLOYED.md (a 2025-11 website deploy note). Closes #151 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QQ7W3CkRKEnBpU5KRQUfUu
1 parent 5d9aa37 commit c4192a9

5 files changed

Lines changed: 80 additions & 291 deletions

File tree

‎WEBSITE_FIXES_DEPLOYED.md‎

Lines changed: 0 additions & 231 deletions
This file was deleted.

‎oilpriceapi/client.py‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -221,20 +221,29 @@ def __init__(
221221
# LTL + parcel carrier fuel surcharges (#101).
222222
self.fuel_surcharge = FuelSurchargeResource(self)
223223

224-
# Initialize visualization (optional)
225-
self.viz: Optional["PriceVisualizer"]
226-
try:
227-
from .visualization import PriceVisualizer
228-
229-
self.viz = PriceVisualizer(self)
230-
except ImportError:
231-
self.viz = None
224+
# Visualization is optional and built on first use of ``viz`` (#151):
225+
# constructing a client must not import matplotlib or warn about it.
226+
self._viz: Optional["PriceVisualizer"] = None
232227

233228
# Initialize telemetry (opt-in, disabled by default)
234229
from .telemetry import Telemetry
235230

236231
self._telemetry = Telemetry(enabled=enable_telemetry)
237232

233+
@property
234+
def viz(self) -> Optional["PriceVisualizer"]:
235+
"""Tufte-style charts, or ``None`` when matplotlib is not installed.
236+
237+
Install with ``pip install matplotlib``.
238+
"""
239+
if self._viz is None:
240+
from .visualization import HAS_MATPLOTLIB, PriceVisualizer
241+
242+
if not HAS_MATPLOTLIB:
243+
return None
244+
self._viz = PriceVisualizer(self)
245+
return self._viz
246+
238247
def request(
239248
self,
240249
method: str,

‎oilpriceapi/visualization.py‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -88,13 +88,8 @@ class PriceVisualizer:
8888
def __init__(self, client):
8989
"""Initialize visualizer with OilPriceAPI client."""
9090
self.client = client
91-
92-
if not HAS_MATPLOTLIB:
93-
warnings.warn(
94-
"matplotlib is required for visualization. "
95-
"Install with: pip install matplotlib",
96-
ImportWarning
97-
)
91+
# No warning here (#151): every plotting method raises ImportError
92+
# with install guidance when matplotlib is missing.
9893

9994
def plot_price_series(
10095
self,

‎test_debug_params.py‎

Lines changed: 0 additions & 45 deletions
This file was deleted.

‎tests/test_lazy_visualization.py‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""#151: constructing a client must not warn about optional matplotlib."""
2+
3+
import subprocess
4+
import sys
5+
import warnings
6+
7+
import pytest
8+
9+
from oilpriceapi import OilPriceAPI
10+
11+
12+
def test_client_construction_emits_no_warning():
13+
with warnings.catch_warnings():
14+
warnings.simplefilter("error")
15+
client = OilPriceAPI(api_key="x")
16+
client.close()
17+
18+
19+
def test_import_and_construct_under_W_error():
20+
# The acceptance check from the issue, in a fresh interpreter so no
21+
# earlier import has already filtered or triggered the warning.
22+
result = subprocess.run(
23+
[
24+
sys.executable,
25+
"-W",
26+
"error",
27+
"-c",
28+
"import oilpriceapi; oilpriceapi.OilPriceAPI(api_key='x').close()",
29+
],
30+
capture_output=True,
31+
text=True,
32+
)
33+
assert result.returncode == 0, result.stderr
34+
35+
36+
def test_construction_does_not_import_matplotlib():
37+
code = (
38+
"import sys, oilpriceapi; c = oilpriceapi.OilPriceAPI(api_key='x'); "
39+
"print('matplotlib' in sys.modules); c.close()"
40+
)
41+
result = subprocess.run(
42+
[sys.executable, "-c", code], capture_output=True, text=True
43+
)
44+
assert result.returncode == 0, result.stderr
45+
assert result.stdout.strip() == "False"
46+
47+
48+
def test_viz_is_none_without_matplotlib_and_object_with_it():
49+
client = OilPriceAPI(api_key="x")
50+
try:
51+
try:
52+
import matplotlib # noqa: F401
53+
except ImportError:
54+
assert client.viz is None
55+
else:
56+
from oilpriceapi.visualization import PriceVisualizer
57+
58+
assert isinstance(client.viz, PriceVisualizer)
59+
assert client.viz is client.viz
60+
finally:
61+
client.close()

0 commit comments

Comments
 (0)