Skip to content

Commit

Permalink
Using os.path.splitext() to support Path objects
Browse files Browse the repository at this point in the history
Using os.path.splitext() is more robust than just str.split().

Additionally, it supports Path objects. Thus, this commit fixes this error:

AttributeError: 'PosixPath' object has no attribute 'split'

Note: it's my first time using type annotations, so it's likely I made some mistake. It is also relevant to add `| Path` to many other function/method signatures, but I'm not doing it in this commit. I leave this as an exercise/suggestion to the maintainer.
  • Loading branch information
denilsonsa authored Nov 23, 2023
1 parent 69c9eae commit 7f4adff
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions layeredimage/io/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Do file io."""
from __future__ import annotations

from os.path import exists
from pathlib import Path
from os.path import exists, splitext

from ..layeredimage import LayeredImage
from .gif import openLayer_GIF, saveLayer_GIF
Expand Down Expand Up @@ -29,7 +30,7 @@ def extNotRecognised(fileName: str):
)


def openLayerImage(file: str) -> LayeredImage:
def openLayerImage(file: str | Path) -> LayeredImage:
"""Open a layer image file into a layer image object.
Args:
Expand Down Expand Up @@ -58,14 +59,14 @@ def openLayerImage(file: str) -> LayeredImage:
if not exists(file):
print(f"ERROR: {file} does not exist")
raise FileExistsError
fileExt = file.split(".")[-1].lower()
fileExt = splitext(file)[1].lower()
if fileExt not in functionMap:
extNotRecognised(file)
raise ValueError
return functionMap[fileExt](file)


def saveLayerImage(fileName: str, layeredImage: LayeredImage) -> None:
def saveLayerImage(fileName: str | Path, layeredImage: LayeredImage) -> None:
"""Save a layered image to a file.
Args:
Expand All @@ -91,7 +92,7 @@ def saveLayerImage(fileName: str, layeredImage: LayeredImage) -> None:
"layered": saveLayer_LAYERED,
"layeredc": saveLayer_LAYEREDC,
}
fileExt = fileName.split(".")[-1].lower()
fileExt = splitext(file)[1].lower()
if fileExt not in functionMap:
extNotRecognised(fileName)
raise ValueError
Expand Down

0 comments on commit 7f4adff

Please sign in to comment.