Commit df6d6cb0 authored by Victor Stinner's avatar Victor Stinner

os: fsencode(), fsdecode() and os.environ(b) internal encode-decode methods

keep a local copy of the fileystem encoding, instead of calling
sys.getfilesystemencoding() each time.

The filesystem encoding is now constant.
parent 2062937a
......@@ -487,12 +487,13 @@ def _createenviron():
data[encodekey(key)] = value
else:
# Where Env Var Names Can Be Mixed Case
encoding = sys.getfilesystemencoding()
def encode(value):
if not isinstance(value, str):
raise TypeError("str expected, not %s" % type(value).__name__)
return value.encode(sys.getfilesystemencoding(), 'surrogateescape')
return value.encode(encoding, 'surrogateescape')
def decode(value):
return value.decode(sys.getfilesystemencoding(), 'surrogateescape')
return value.decode(encoding, 'surrogateescape')
encodekey = encode
data = environ
return _Environ(data,
......@@ -535,7 +536,14 @@ if supports_bytes_environ:
__all__.extend(("environb", "getenvb"))
def fsencode(filename):
def _fscodec():
encoding = sys.getfilesystemencoding()
if encoding == 'mbcs':
errors = None # strict
else:
errors = 'surrogateescape'
def fsencode(filename):
"""
Encode filename to the filesystem encoding with 'surrogateescape' error
handler, return bytes unchanged. On Windows, use 'strict' error handler if
......@@ -544,15 +552,11 @@ def fsencode(filename):
if isinstance(filename, bytes):
return filename
elif isinstance(filename, str):
encoding = sys.getfilesystemencoding()
if encoding == 'mbcs':
return filename.encode(encoding)
else:
return filename.encode(encoding, 'surrogateescape')
return filename.encode(encoding, errors)
else:
raise TypeError("expect bytes or str, not %s" % type(filename).__name__)
def fsdecode(filename):
def fsdecode(filename):
"""
Decode filename from the filesystem encoding with 'surrogateescape' error
handler, return str unchanged. On Windows, use 'strict' error handler if
......@@ -561,14 +565,15 @@ def fsdecode(filename):
if isinstance(filename, str):
return filename
elif isinstance(filename, bytes):
encoding = sys.getfilesystemencoding()
if encoding == 'mbcs':
return filename.decode(encoding)
else:
return filename.decode(encoding, 'surrogateescape')
return filename.decode(encoding, errors)
else:
raise TypeError("expect bytes or str, not %s" % type(filename).__name__)
return fsencode, fsdecode
fsencode, fsdecode = _fscodec()
del _fscodec
def _exists(name):
return name in globals()
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment