Summary
MetricWriter currently only accepts a file path, requiring users to write to actual files. It would be more flexible to accept an IO or TextIOWrapper directly, enabling writing to any IO source.
Context
From #6 (comment) (@clintval):
It'd be nice if this accepted an IO or io.TextIOWrapper and a classmethod def from_path() handled the opening of the file. That way, users could read metrics from any IO source without having to mock them up into files.
Suggested Solution
Refactor MetricWriter.__init__ to accept an IO handle directly, and add a from_path() classmethod for file-based usage. Use an ownership flag to determine whether the writer should close the handle on exit.
- Introduce a new
_owns_handle: bool attribute on MetricWriter
__init__ sets _owns_handle = False by default, so when working with a passed IO object the caller manages the lifecycle of the handle
from_path() opens the file and sets _owns_handle = True, so the handle is closed on exit of the writer
MetricWriter should remain a context manager in both cases
Summary
MetricWritercurrently only accepts a file path, requiring users to write to actual files. It would be more flexible to accept anIOorTextIOWrapperdirectly, enabling writing to any IO source.Context
From #6 (comment) (@clintval):
Suggested Solution
Refactor
MetricWriter.__init__to accept an IO handle directly, and add afrom_path()classmethod for file-based usage. Use an ownership flag to determine whether the writer should close the handle on exit._owns_handle: boolattribute onMetricWriter__init__sets_owns_handle = Falseby default, so when working with a passedIOobject the caller manages the lifecycle of the handlefrom_path()opens the file and sets_owns_handle = True, so the handle is closed on exit of the writerMetricWritershould remain a context manager in both cases