Skip to content

Commit b82b3e7

Browse files
committed
remove explicit use of temp folder; address pylint issues
1 parent adc2c60 commit b82b3e7

File tree

10 files changed

+200
-195
lines changed

10 files changed

+200
-195
lines changed

sigmf/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
# SPDX-License-Identifier: LGPL-3.0-or-later
66

77
# version of this python module
8-
__version__ = "1.2.7"
8+
__version__ = "1.2.8"
99
# matching version of the SigMF specification
1010
__specification__ = "1.2.3"
1111

sigmf/archive.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -129,10 +129,10 @@ def _resolve(self, name, fileobj):
129129
arcname = path.stem
130130
else:
131131
arcname = name
132-
except io.UnsupportedOperation:
133-
raise SigMFFileError(f"fileobj {fileobj} is not byte-writable.")
134-
except AttributeError:
135-
raise SigMFFileError(f"fileobj {fileobj} is invalid.")
132+
except io.UnsupportedOperation as exc:
133+
raise SigMFFileError(f"fileobj {fileobj} is not byte-writable.") from exc
134+
except AttributeError as exc:
135+
raise SigMFFileError(f"fileobj {fileobj} is invalid.") from exc
136136
elif name:
137137
path = Path(name)
138138
# ensure name has correct suffix if it exists
@@ -146,8 +146,8 @@ def _resolve(self, name, fileobj):
146146

147147
try:
148148
fileobj = open(path, "wb")
149-
except (OSError, IOError):
150-
raise SigMFFileError(f"Can't open {name} for writing.")
149+
except (OSError, IOError) as exc:
150+
raise SigMFFileError(f"Can't open {name} for writing.") from exc
151151
else:
152152
raise SigMFFileError("Either `name` or `fileobj` needs to be defined.")
153153

sigmf/archivereader.py

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,27 +7,18 @@
77
"""Access SigMF archives without extracting them."""
88

99
import io
10-
import os
11-
import shutil
1210
import tarfile
13-
import tempfile
1411
from pathlib import Path
1512

1613
from . import __version__
17-
from .archive import (
18-
SIGMF_ARCHIVE_EXT,
19-
SIGMF_DATASET_EXT,
20-
SIGMF_METADATA_EXT,
21-
SigMFArchive,
22-
)
14+
from .archive import SIGMF_ARCHIVE_EXT, SIGMF_DATASET_EXT, SIGMF_METADATA_EXT
2315
from .error import SigMFFileError
2416
from .sigmffile import SigMFFile
25-
from .utils import dict_merge
2617

2718

2819
class SigMFArchiveReader:
2920
"""
30-
Access data within SigMF archive `tar` in-place without extracting.
21+
Access data within SigMF archive tarball in-place without extracting.
3122
3223
Parameters
3324
----------
@@ -44,6 +35,10 @@ class SigMFArchiveReader:
4435
------
4536
SigMFError
4637
Archive file does not exist or is improperly formatted.
38+
ValueError
39+
If invalid arguments.
40+
ValidationError
41+
If metadata is invalid.
4742
"""
4843

4944
def __init__(self, name=None, skip_checksum=False, map_readonly=True, archive_buffer=None):
@@ -96,7 +91,7 @@ def __init__(self, name=None, skip_checksum=False, map_readonly=True, archive_bu
9691
raise SigMFFileError("No .sigmf-data file found in archive!")
9792

9893
self.sigmffile = SigMFFile(metadata=json_contents)
99-
valid_md = self.sigmffile.validate()
94+
self.sigmffile.validate()
10095

10196
self.sigmffile.set_data_file(
10297
data_buffer=data_buffer,

sigmf/schema.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
from pathlib import Path
1111

1212
from . import __version__ as toolversion
13-
from . import utils
1413

1514
SCHEMA_META = "schema-meta.json"
1615
SCHEMA_COLLECTION = "schema-collection.json"

sigmf/sigmffile.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,6 @@
99
import codecs
1010
import io
1111
import json
12-
import tarfile
13-
import tempfile
1412
import warnings
1513
from collections import OrderedDict
1614
from pathlib import Path
@@ -229,7 +227,7 @@ def __getitem__(self, sli):
229227
ray = mem[:, :, 0].astype(self._return_type) + 1.0j * mem[:, :, 1].astype(self._return_type)
230228
else:
231229
raise ValueError("unhandled ndim in SigMFFile.__getitem__(); this shouldn't happen")
232-
return ray[0] if type(sli) is int else ray # return element instead of 1-element array
230+
return ray[0] if isinstance(sli, int) else ray # return element instead of 1-element array
233231

234232
def _get_start_offset(self):
235233
"""

sigmf/utils.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,10 @@
1010
import sys
1111
from copy import deepcopy
1212
from datetime import datetime, timezone
13-
from pathlib import Path
1413

1514
import numpy as np
1615

17-
from . import error
16+
from .error import SigMFError
1817

1918
SIGMF_DATETIME_ISO8601_FMT = "%Y-%m-%dT%H:%M:%S.%fZ"
2019

@@ -75,7 +74,7 @@ def dict_merge(a_dict: dict, b_dict: dict) -> dict:
7574
def get_endian_str(ray: np.ndarray) -> str:
7675
"""Return SigMF compatible endianness string for a numpy array"""
7776
if not isinstance(ray, np.ndarray):
78-
raise error.SigMFError("Argument must be a numpy array")
77+
raise SigMFError("Argument must be a numpy array")
7978
atype = ray.dtype
8079

8180
if atype.byteorder == "<":
@@ -94,10 +93,10 @@ def get_data_type_str(ray: np.ndarray) -> str:
9493
integer types are not supported.
9594
"""
9695
if not isinstance(ray, np.ndarray):
97-
raise error.SigMFError("Argument must be a numpy array")
96+
raise SigMFError("Argument must be a numpy array")
9897
atype = ray.dtype
9998
if atype.kind not in ("u", "i", "f", "c"):
100-
raise error.SigMFError("Unsupported data type:", atype)
99+
raise SigMFError("Unsupported data type:", atype)
101100
data_type_str = ""
102101
if atype.kind == "c":
103102
data_type_str += "cf"

sigmf/validate.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,10 +136,10 @@ def main(arg_tuple: Optional[Tuple[str, ...]] = None) -> None:
136136
log.error("No paths to validate.")
137137
sys.exit(1)
138138
elif n_completed != n_total:
139-
log.info(f"Validated {n_completed} of {n_total} files OK")
139+
log.info("Validated %d of %d files OK", n_completed, n_total)
140140
sys.exit(1)
141141
else:
142-
log.info(f"Validated all {n_total} files OK!")
142+
log.info("Validated all %d files OK!", n_total)
143143

144144

145145
if __name__ == "__main__":

tests/test_archivereader.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66

77
"""Tests for SigMFArchiveReader"""
88

9-
import tempfile
109
import unittest
10+
from tempfile import NamedTemporaryFile
1111

1212
import numpy as np
1313

@@ -33,29 +33,28 @@ def setUp(self):
3333

3434
def test_access_data_without_untar(self):
3535
"""iterate through datatypes and verify IO is correct"""
36-
_, temp_path = tempfile.mkstemp()
37-
_, temp_archive = tempfile.mkstemp(suffix=".sigmf")
36+
temp_data = NamedTemporaryFile()
37+
temp_archive = NamedTemporaryFile(suffix=".sigmf")
3838

3939
for key, dtype in self.lut.items():
4040
# for each type of storage
4141
temp_samples = np.arange(self.raw_count, dtype=dtype)
42-
temp_samples.tofile(temp_path)
42+
temp_samples.tofile(temp_data.name)
4343
for num_channels in [1, 4, 8]:
4444
# for single or 8 channel
4545
for complex_prefix in ["r", "c"]:
4646
# for real or complex
4747
target_count = self.raw_count
4848
temp_meta = SigMFFile(
49-
data_file=temp_path,
49+
data_file=temp_data.name,
5050
global_info={
5151
SigMFFile.DATATYPE_KEY: f"{complex_prefix}{key}_le",
5252
SigMFFile.NUM_CHANNELS_KEY: num_channels,
53-
SigMFFile.VERSION_KEY: __specification__,
5453
},
5554
)
56-
temp_meta.tofile(temp_archive, toarchive=True)
55+
temp_meta.tofile(temp_archive.name, toarchive=True)
5756

58-
readback = SigMFArchiveReader(temp_archive)
57+
readback = SigMFArchiveReader(temp_archive.name)
5958
readback_samples = readback[:]
6059

6160
if complex_prefix == "c":
@@ -84,10 +83,10 @@ def test_access_data_without_untar(self):
8483

8584

8685
def test_archiveread_data_file_unchanged(test_sigmffile):
87-
with tempfile.NamedTemporaryFile(suffix=".sigmf") as temp:
86+
with NamedTemporaryFile(suffix=".sigmf") as temp_file:
8887
input_samples = test_sigmffile.read_samples()
89-
test_sigmffile.archive(temp.name)
90-
arc = sigmf.sigmffile.fromfile(temp.name)
88+
test_sigmffile.archive(temp_file.name)
89+
arc = sigmf.sigmffile.fromfile(temp_file.name)
9190
output_samples = arc.read_samples()
9291

9392
assert np.array_equal(input_samples, output_samples)

0 commit comments

Comments
 (0)