Skip to content

Commit

Permalink
Remove Python 2 compat code.
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 473306343
Change-Id: I4c166f7fa34ce2f1b0bcacafbf790d4f932886d1
  • Loading branch information
Abseil Team authored and copybara-github committed Sep 9, 2022
1 parent d172459 commit b825efe
Show file tree
Hide file tree
Showing 5 changed files with 12 additions and 63 deletions.
8 changes: 4 additions & 4 deletions absl/flags/_argument_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ class ArgumentSerializer(object):

def serialize(self, value):
"""Returns a serialized string of the value."""
return _helpers.str_or_unicode(value)
return str(value)


class NumericParser(ArgumentParser):
Expand Down Expand Up @@ -454,7 +454,7 @@ def __init__(self, list_sep):

def serialize(self, value):
"""See base class."""
return self.list_sep.join([_helpers.str_or_unicode(x) for x in value])
return self.list_sep.join([str(x) for x in value])


class EnumClassListSerializer(ListSerializer):
Expand Down Expand Up @@ -498,7 +498,7 @@ def serialize(self, value):

# We need the returned value to be pure ascii or Unicodes so that
# when the xml help is generated they are usefully encodable.
return _helpers.str_or_unicode(serialized_value)
return str(serialized_value)


class EnumClassSerializer(ArgumentSerializer):
Expand All @@ -514,7 +514,7 @@ def __init__(self, lowercase):

def serialize(self, value):
"""Returns a serialized string of the Enum class value."""
as_string = _helpers.str_or_unicode(value.name)
as_string = str(value.name)
return as_string.lower() if self._lowercase else as_string


Expand Down
2 changes: 1 addition & 1 deletion absl/flags/_flag.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ def _get_parsed_value_as_string(self, value):
return repr('true')
else:
return repr('false')
return repr(_helpers.str_or_unicode(value))
return repr(str(value))

def parse(self, argument):
"""Parses string and sets flag value.
Expand Down
10 changes: 3 additions & 7 deletions absl/flags/_flagvalues.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,11 +412,7 @@ def __setitem__(self, name, flag):
fl = self._flags()
if not isinstance(flag, _flag.Flag):
raise _exceptions.IllegalFlagValueError(flag)
if str is bytes and isinstance(name, unicode):
# When using Python 2 with unicode_literals, allow it but encode it
# into the bytes type we require.
name = name.encode('utf-8')
if not isinstance(name, type('')):
if not isinstance(name, str):
raise _exceptions.Error('Flag name must be a string')
if not name:
raise _exceptions.Error('Flag name cannot be empty')
Expand Down Expand Up @@ -632,7 +628,7 @@ def __call__(self, argv, known_only=False):
TypeError: Raised on passing wrong type of arguments.
ValueError: Raised on flag value parsing error.
"""
if _helpers.is_bytes_or_string(argv):
if isinstance(argv, (str, bytes)):
raise TypeError(
'argv should be a tuple/list of strings, not bytes or string.')
if not argv:
Expand Down Expand Up @@ -1006,7 +1002,7 @@ def get_flag_value(self, name, default): # pylint: disable=invalid-name

def _is_flag_file_directive(self, flag_string):
"""Checks whether flag_string contain a --flagfile=<foo> directive."""
if isinstance(flag_string, type('')):
if isinstance(flag_string, str):
if flag_string.startswith('--flagfile='):
return 1
elif flag_string == '--flagfile':
Expand Down
40 changes: 4 additions & 36 deletions absl/flags/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@


_DEFAULT_HELP_WIDTH = 80 # Default width of help output.
_MIN_HELP_WIDTH = 40 # Minimal "sane" width of help output. We assume that any
# value below 40 is unreasonable.
# Minimal "sane" width of help output. We assume that any value below 40 is
# unreasonable.
_MIN_HELP_WIDTH = 40

# Define the allowed error rate in an input string to get suggestions.
#
Expand Down Expand Up @@ -125,32 +126,6 @@ def get_calling_module():
return get_calling_module_object_and_name().module_name


def str_or_unicode(value):
"""Converts a value to a python string.
Behavior of this function is intentionally different in Python2/3.
In Python2, the given value is attempted to convert to a str (byte string).
If it contains non-ASCII characters, it is converted to a unicode instead.
In Python3, the given value is always converted to a str (unicode string).
This behavior reflects the (bad) practice in Python2 to try to represent
a string as str as long as it contains ASCII characters only.
Args:
value: An object to be converted to a string.
Returns:
A string representation of the given value. See the description above
for its type.
"""
try:
return str(value)
except UnicodeEncodeError:
return unicode(value) # Python3 should never come here


def create_xml_dom_element(doc, name, value):
"""Returns an XML DOM element with name and text value.
Expand All @@ -164,7 +139,7 @@ def create_xml_dom_element(doc, name, value):
Returns:
An instance of minidom.Element.
"""
s = str_or_unicode(value)
s = str(value)
if isinstance(value, bool):
# Display boolean values as the C++ flag library does: no caps.
s = s.lower()
Expand Down Expand Up @@ -424,10 +399,3 @@ def doc_to_help(doc):
doc = re.sub(r'(?<=\S)\n(?=\S)', ' ', doc, flags=re.M)

return doc


def is_bytes_or_string(maybe_string):
if str is bytes:
return isinstance(maybe_string, basestring)
else:
return isinstance(maybe_string, (str, bytes))
15 changes: 0 additions & 15 deletions absl/flags/tests/_helpers_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,20 +150,5 @@ def iteritems(self):
sys.modules = orig_sys_modules


class IsBytesOrString(absltest.TestCase):

def test_bytes(self):
self.assertTrue(_helpers.is_bytes_or_string(b'bytes'))

def test_str(self):
self.assertTrue(_helpers.is_bytes_or_string('str'))

def test_unicode(self):
self.assertTrue(_helpers.is_bytes_or_string(u'unicode'))

def test_list(self):
self.assertFalse(_helpers.is_bytes_or_string(['str']))


if __name__ == '__main__':
absltest.main()

0 comments on commit b825efe

Please sign in to comment.