Skip to content

Support IO streams in MetricWriter #9

@msto

Description

@msto

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.

  1. Introduce a new _owns_handle: bool attribute on MetricWriter
  2. __init__ sets _owns_handle = False by default, so when working with a passed IO object the caller manages the lifecycle of the handle
  3. 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions