Skip to content

Commit

Permalink
Merge pull request #170 from mwcraig/add-overwrite
Browse files Browse the repository at this point in the history
Add overwrite argument to save method
  • Loading branch information
mwcraig authored Jul 7, 2023
2 parents ebf8da2 + b2ec100 commit c0ec34a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
14 changes: 13 additions & 1 deletion astrowidgets/ginga.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

# STDLIB
import functools
from pathlib import Path
import warnings

# THIRD-PARTY
Expand Down Expand Up @@ -973,12 +974,23 @@ def scroll_pan(self, value):
else:
bindmap.map_event(None, (), 'pa_pan', 'zoom')

def save(self, filename):
def save(self, filename, overwrite=False):
"""
Save out the current image view to given PNG filename.
Parameters
----------
filename : str
Name of file to save to.
overwrite : bool, optional
If `True`, overwrite existing file.
"""
# It turns out the image value is already in PNG format so we just
# to write that out to a file.
if not overwrite and Path.exists(filename):
raise FileExistsError(f'File {filename} exists and overwrite=False')

with open(filename, 'wb') as f:
f.write(self._jup_img.value)

Expand Down
6 changes: 5 additions & 1 deletion astrowidgets/interface_definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def load_nddata(self, data: NDData) -> None:

# Saving contents of the view and accessing the view
@abstractmethod
def save(self, filename: str | os.PathLike) -> None:
def save(self, filename: str | os.PathLike, overwrite: bool = False) -> None:
"""
Save the current view to a file.
Expand All @@ -99,6 +99,10 @@ def save(self, filename: str | os.PathLike) -> None:
filename : str
The file to save to. The format is determined by the
extension.
overwrite : bool, optional
If `True`, overwrite the file if it exists. Default is
`False`.
"""
raise NotImplementedError

Expand Down
13 changes: 13 additions & 0 deletions astrowidgets/tests/widget_api_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,3 +359,16 @@ def test_scroll_pan(self):
def test_save(self, tmp_path):
filename = tmp_path / 'woot.png'
self.image.save(filename)

def test_save_overwrite(self, tmp_path):
filename = tmp_path / 'woot.png'

# First write should be fine
self.image.save(filename)

# Second write should raise an error because file exists
with pytest.raises(FileExistsError):
self.image.save(filename)

# Using overwrite should save successfully
self.image.save(filename, overwrite=True)

0 comments on commit c0ec34a

Please sign in to comment.