55"""
66
77from abc import ABCMeta
8+ from typing import Optional , Union , cast
9+
10+ from can .typechecking import FileLike , PathLike
811
912
1013class BaseIOHandler (metaclass = ABCMeta ):
1114 """A generic file handler that can be used for reading and writing.
1215
1316 Can be used as a context manager.
1417
15- :attr file-like file:
18+ :attr Optional[FileLike] file:
1619 the file-like object that is kept internally, or None if none
1720 was opened
1821 """
1922
20- def __init__ (self , file , mode = "rt" ):
23+ def __init__ (self , file : Optional [ Union [ FileLike , PathLike ]], mode : str = "rt" ):
2124 """
2225 :param file: a path-like object to open a file, a file-like object
2326 to be used as a file or `None` to not use a file at all
24- :param str mode: the mode that should be used to open the file, see
25- :func:`open`, ignored if *file* is `None`
27+ :param mode: the mode that should be used to open the file, see
28+ :func:`open`, ignored if *file* is `None`
2629 """
2730 if file is None or (hasattr (file , "read" ) and hasattr (file , "write" )):
2831 # file is None or some file-like object
29- self .file = file
32+ self .file = cast ( Optional [ FileLike ], file )
3033 else :
3134 # file is some path-like object
32- self .file = open (file , mode )
35+ self .file = open (cast ( PathLike , file ) , mode )
3336
3437 # for multiple inheritance
3538 super ().__init__ ()
@@ -41,6 +44,7 @@ def __exit__(self, *args):
4144 self .stop ()
4245
4346 def stop (self ):
47+ """Closes the undelying file-like object and flushes it, if it was opened in write mode."""
4448 if self .file is not None :
4549 # this also implies a flush()
4650 self .file .close ()
0 commit comments