Skip to content

Commit 32d4d37

Browse files
committed
import_od: Accept os.PathLike with robust suffix handling.
Utilize the standard library's os.path.splitext() function to find the file name suffix (case-insensitive). Fix a [union-attr] static type check error using an empty string as fallback for the file name on file-like objects. The annotated TextIO type does provide it, but mypy cannot infer that connection between with the "read" method being available. Failing with the ValueError in case the attribute is missing is still better than letting out an AttributeError.
1 parent 950edc0 commit 32d4d37

1 file changed

Lines changed: 8 additions & 7 deletions

File tree

canopen/objectdictionary/__init__.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ def export_od(
7575

7676

7777
def import_od(
78-
source: Union[str, TextIO, None],
78+
source: Union[str, os.PathLike, TextIO, None],
7979
node_id: Optional[int] = None,
8080
) -> ObjectDictionary:
8181
"""Parse an EDS, DCF, or EPF file.
@@ -92,16 +92,17 @@ def import_od(
9292
"""
9393
if source is None:
9494
return ObjectDictionary()
95-
if hasattr(source, "read"):
95+
filename = ""
96+
if isinstance(source, (str, os.PathLike)):
97+
# Path to file
98+
filename = os.fspath(source)
99+
elif hasattr(source, "read"):
96100
# File like object
97-
filename = source.name
101+
filename = getattr(source, "name", "")
98102
elif hasattr(source, "tag"):
99103
# XML tree, probably from an EPF file
100104
filename = "od.epf"
101-
else:
102-
# Path to file
103-
filename = source
104-
suffix = filename[filename.rfind("."):].lower()
105+
_, suffix = os.path.splitext(filename.lower())
105106
if suffix in (".eds", ".dcf"):
106107
from canopen.objectdictionary import eds
107108
return eds.import_eds(source, node_id)

0 commit comments

Comments
 (0)