Skip to content

Commit 2a7596e

Browse files
karlwaldmanclaude
andcommitted
fix: client.viz raises ImportError naming the viz extra without matplotlib (#151)
Adversarial review of #157 found client.viz returned None when matplotlib was missing, so client.viz.plot_* failed with a bare AttributeError. The viz property now always builds a cached PriceVisualizer lazily (no import, no warning at construction), and each plotting method raises ImportError: "matplotlib is required for visualization. Install it with: pip install 'oilpriceapi[viz]'". Adds the viz extra to pyproject. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QQ7W3CkRKEnBpU5KRQUfUu
1 parent c4192a9 commit 2a7596e

5 files changed

Lines changed: 82 additions & 26 deletions

File tree

‎examples/visualization_demo.py‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
1414

1515
from oilpriceapi import OilPriceAPI
16+
from oilpriceapi.visualization import HAS_MATPLOTLIB
1617

1718
# Configuration
1819
API_KEY = os.getenv("OILPRICEAPI_KEY")
@@ -30,8 +31,8 @@ def demo_price_series():
3031

3132
client = OilPriceAPI(api_key=API_KEY, base_url=BASE_URL)
3233

33-
if not client.viz:
34-
print("⚠️ Matplotlib not installed. Install with: pip install matplotlib")
34+
if not HAS_MATPLOTLIB:
35+
print("⚠️ Matplotlib not installed. Install with: pip install 'oilpriceapi[viz]'")
3536
return
3637

3738
# Create visualization
@@ -76,7 +77,7 @@ def demo_spread_analysis():
7677

7778
client = OilPriceAPI(api_key=API_KEY, base_url=BASE_URL)
7879

79-
if not client.viz:
80+
if not HAS_MATPLOTLIB:
8081
print("⚠️ Visualization not available")
8182
return
8283

@@ -112,7 +113,7 @@ def demo_sparklines():
112113

113114
client = OilPriceAPI(api_key=API_KEY, base_url=BASE_URL)
114115

115-
if not client.viz:
116+
if not HAS_MATPLOTLIB:
116117
print("⚠️ Visualization not available")
117118
return
118119

@@ -146,7 +147,7 @@ def demo_small_multiples():
146147

147148
client = OilPriceAPI(api_key=API_KEY, base_url=BASE_URL)
148149

149-
if not client.viz:
150+
if not HAS_MATPLOTLIB:
150151
print("⚠️ Visualization not available")
151152
return
152153

@@ -191,7 +192,7 @@ def main():
191192
print(f"\n✅ Matplotlib version: {matplotlib.__version__}")
192193
except ImportError:
193194
print("\n⚠️ Matplotlib not installed!")
194-
print(" Install with: pip install matplotlib")
195+
print(" Install with: pip install 'oilpriceapi[viz]'")
195196
return
196197

197198
# Run demos

‎oilpriceapi/client.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -231,16 +231,16 @@ def __init__(
231231
self._telemetry = Telemetry(enabled=enable_telemetry)
232232

233233
@property
234-
def viz(self) -> Optional["PriceVisualizer"]:
235-
"""Tufte-style charts, or ``None`` when matplotlib is not installed.
234+
def viz(self) -> "PriceVisualizer":
235+
"""Tufte-style charts, built on first access.
236236
237-
Install with ``pip install matplotlib``.
237+
Building the visualizer imports nothing optional and never warns. If
238+
matplotlib is missing, each plotting method raises ``ImportError``
239+
naming the extra: ``pip install 'oilpriceapi[viz]'``.
238240
"""
239241
if self._viz is None:
240-
from .visualization import HAS_MATPLOTLIB, PriceVisualizer
242+
from .visualization import PriceVisualizer
241243

242-
if not HAS_MATPLOTLIB:
243-
return None
244244
self._viz = PriceVisualizer(self)
245245
return self._viz
246246

‎oilpriceapi/visualization.py‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,13 @@
2323
except ImportError:
2424
HAS_MATPLOTLIB = False
2525

26+
# Raised by every plotting method when matplotlib is not installed. It names
27+
# the extra so the fix is one copy-paste away.
28+
MATPLOTLIB_REQUIRED = (
29+
"matplotlib is required for visualization. "
30+
"Install it with: pip install 'oilpriceapi[viz]'"
31+
)
32+
2633
try:
2734
import pandas as pd
2835
HAS_PANDAS = True
@@ -114,7 +121,7 @@ def plot_price_series(
114121
matplotlib Figure object
115122
"""
116123
if not HAS_MATPLOTLIB:
117-
raise ImportError("matplotlib required for visualization")
124+
raise ImportError(MATPLOTLIB_REQUIRED)
118125

119126
# Fetch data
120127
history = self.client.historical.get(
@@ -233,7 +240,7 @@ def plot_spread(
233240
Following Tufte's principle of showing data relationships clearly.
234241
"""
235242
if not HAS_MATPLOTLIB:
236-
raise ImportError("matplotlib required for visualization")
243+
raise ImportError(MATPLOTLIB_REQUIRED)
237244

238245
# Fetch data for both commodities
239246
hist1 = self.client.historical.get(
@@ -376,7 +383,7 @@ def create_sparkline(
376383
Perfect for embedding in reports or dashboards.
377384
"""
378385
if not HAS_MATPLOTLIB:
379-
raise ImportError("matplotlib required for visualization")
386+
raise ImportError(MATPLOTLIB_REQUIRED)
380387

381388
# Fetch recent data
382389
end_date = datetime.now()
@@ -437,7 +444,7 @@ def create_small_multiples(
437444
Allows easy comparison across multiple commodities.
438445
"""
439446
if not HAS_MATPLOTLIB:
440-
raise ImportError("matplotlib required for visualization")
447+
raise ImportError(MATPLOTLIB_REQUIRED)
441448

442449
n = len(commodities)
443450
rows = (n + cols - 1) // cols

‎pyproject.toml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,11 @@ cli = [
6565
"click>=8.0.0",
6666
"rich>=13.0.0",
6767
]
68+
viz = [
69+
"matplotlib>=3.5.0",
70+
"numpy>=1.20.0",
71+
"pandas>=1.5.0",
72+
]
6873
all = [
6974
"oilpriceapi[pandas,async,stream,cache,cli]",
7075
]

‎tests/test_lazy_visualization.py‎

Lines changed: 53 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -45,17 +45,60 @@ def test_construction_does_not_import_matplotlib():
4545
assert result.stdout.strip() == "False"
4646

4747

48-
def test_viz_is_none_without_matplotlib_and_object_with_it():
48+
# Simulates an install without matplotlib: a None entry in sys.modules makes
49+
# ``import matplotlib`` raise ImportError in a fresh interpreter.
50+
_NO_MPL = (
51+
"import sys; sys.modules['matplotlib'] = None; "
52+
"sys.modules['matplotlib.pyplot'] = None; "
53+
)
54+
55+
56+
@pytest.mark.parametrize(
57+
"call",
58+
[
59+
"c.viz.plot_price_series('WTI_USD')",
60+
"c.viz.plot_spread('BRENT_CRUDE_USD', 'WTI_USD')",
61+
"c.viz.create_sparkline([1.0, 2.0])",
62+
"c.viz.create_small_multiples(['WTI_USD'])",
63+
],
64+
)
65+
def test_plotting_without_matplotlib_names_the_extra(call):
66+
# Review of #157: client.viz returned None without matplotlib, so every
67+
# documented ``client.viz.plot_*`` call died with a bare AttributeError.
68+
code = (
69+
_NO_MPL
70+
+ "import oilpriceapi; c = oilpriceapi.OilPriceAPI(api_key='x')\n"
71+
+ "try:\n"
72+
+ f" {call}\n"
73+
+ "except ImportError as e:\n"
74+
+ " print('IMPORTERROR:' + str(e))\n"
75+
+ "except Exception as e:\n"
76+
+ " print('OTHER:' + type(e).__name__ + ':' + str(e))\n"
77+
+ "c.close()"
78+
)
79+
result = subprocess.run(
80+
[sys.executable, "-W", "error", "-c", code], capture_output=True, text=True
81+
)
82+
assert result.returncode == 0, result.stderr
83+
out = result.stdout.strip()
84+
assert out.startswith("IMPORTERROR:"), out
85+
assert "pip install 'oilpriceapi[viz]'" in out, out
86+
87+
88+
def test_construction_without_matplotlib_is_warning_free():
89+
code = _NO_MPL + "import oilpriceapi; oilpriceapi.OilPriceAPI(api_key='x').close()"
90+
result = subprocess.run(
91+
[sys.executable, "-W", "error", "-c", code], capture_output=True, text=True
92+
)
93+
assert result.returncode == 0, result.stderr
94+
95+
96+
def test_viz_is_a_cached_visualizer():
97+
from oilpriceapi.visualization import PriceVisualizer
98+
4999
client = OilPriceAPI(api_key="x")
50100
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
101+
assert isinstance(client.viz, PriceVisualizer)
102+
assert client.viz is client.viz
60103
finally:
61104
client.close()

0 commit comments

Comments
 (0)