Skip to content

Commit 6253cd6

Browse files
committed
Fix #5: bug with identifying file-like objects
The `file` class was removed in python 3, and it's more robust to use duck typing in any case.
1 parent 81b69b5 commit 6253cd6

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

Polygon/IO.py

+23-4
Original file line numberDiff line numberDiff line change
@@ -67,25 +67,44 @@ def __call__(self):
6767

6868

6969
def getWritableObject(ofile):
70-
"""try to make a writable file-like object from argument"""
70+
"""try to make a writable file-like object from argument. If the argument is None,
71+
construct a new StringIO for writing
72+
73+
The second return value indicates whether the returned value needs to be closed.
74+
Note that if a file-like object was passed in, it is assumed that this object
75+
will be closed by the code that created it.
76+
77+
:Arguments:
78+
- ofile: file-like object, string with the filename, or None
79+
:Returns:
80+
- a file-like object
81+
- a bool indicating whether the file should be closed after writing
82+
"""
7183
if ofile is None:
7284
return StringIO(), False
7385
elif type(ofile) == str:
7486
return open(ofile, 'w'), True
75-
elif type(ofile) in (file, StringIO):
87+
elif hasattr(ofile,'write'):
7688
return ofile, False
7789
else:
7890
raise Exception("Can't make a writable object from argument!")
7991

8092

8193
def getReadableObject(ifile):
82-
"""try to make a readable file-like object from argument"""
94+
"""try to make a readable file-like object from argument
95+
96+
:Arguments:
97+
- ifile: file-like object or string with the filename
98+
:Returns:
99+
- a file-like object
100+
- a bool indicating whether the file should be closed after reading
101+
"""
83102
if type(ifile) == str:
84103
try:
85104
return open(ifile, 'r'), True
86105
except:
87106
return StringIO(ifile), True
88-
elif type(ifile) in (file, StringIO):
107+
elif hasattr(ifile,'read'):
89108
return ifile, False
90109
else:
91110
raise Exception("Can't make a readable object from argument!")

0 commit comments

Comments
 (0)