[Python-Dev] Pathlib enhancements - acceptable inputs and outputs for fspath and os.fspath() (original) (raw)

Random832 random832 at fastmail.com
Mon Apr 11 14🔞08 EDT 2016


On Mon, Apr 11, 2016, at 13:36, Brett Cannon wrote:

How about we take something from the "explicit is better than implicit" playbook and add a keyword argument to os.fspath() to allow bytes to pass through?

Except, we already know how to convert a bytes-path into a str (and vice versa) with sys.getfilesystemencoding and surrogateescape. So why not just have the argument specify what return type is desired?

def fspath(path, *, want_bytes=False): if isinstance(path, (bytes, str)): ppath = path else: try: ppath = path.fspath() except AttributeError: raise TypeError if isinstance(ppath, str): return ppath.encode(...) if want_bytes else ppath elif isinstance(ppath, bytes): return ppath if want_bytes else ppath.decode(...) else: raise TypeError

This way the posix os module can call the function and have the bytes value already prepared for it to pass to the real open() syscall.

You could even add the same thing in other places, e.g. os.path.join (defaulting to if the first argument is a bytes).



More information about the Python-Dev mailing list