Movatterモバイル変換
[0]ホーム
[Python-ideas] tweaking the file system path protocol
Koos Zevenhovenk7hoven at gmail.com
Fri May 26 09:20:39 EDT 2017
Accidentally sent the email before it was done. Additions / corrections below:On Fri, May 26, 2017 at 3:58 PM, Koos Zevenhoven <k7hoven at gmail.com> wrote:> On Wed, May 24, 2017 at 5:52 PM, Wolfgang Maier>>>> - makes the "path.__fspath__() if hasattr(path, "__fspath__") else path">> idiom consistent for subclasses of str and bytes that define __fspath__>>>> One can discuss whether this is the best idiom to use (I did not write> it, so maybe someone else has comments).>> Anyway, some may want to use>> path.__fspath__() if hasattr(path, "__fspath__") else str(path)>> and some may want>> path if isinstance(path, (str, bytes)) else path.__fspath__()>> Or others may not be after oneliners like this and instead include the> full implementation of fspath in their code—or even better, with some> modifications.>> Really, the best thing to use in pre-3.6 might be more like:>> def fspath(path):> if isinstance(path, (str, bytes)):> return path> if hasattr(path, '__fspath__'):> return path.__fspath__()> if type(path).__name__ == 'DirEntry':> return path.path> if isinstance(path, pathlib.PurePath):> return str(path)> raise TypeError("Argument cannot be interpreted as a file system path: " + repr(path))>In the above, I have to check type(path).__name__, because DirEntrywas not exposed as os.DirEntry in 3.5 yet.For pre-3.4 Python and for older third-party libraries that do inheritfrom str/bytes, one could even use something like:def fspath(path): if isinstance(path, (str, bytes)): return path if hasattr(type(path), '__fspath__'): return type(path).__fspath__(path) if type(path).__name__ == 'DirEntry': return path.path if "Path" in type(path).__name__: # add whatever known names forpath classes (what a hack!) return str(path) raise TypeError("Argument cannot be interpreted as a file systempath: " + repr(path))—Koos-- + Koos Zevenhoven +http://twitter.com/k7hoven +
More information about the Python-ideasmailing list
[8]ページ先頭