Remove the use of six in absl.flags.

PiperOrigin-RevId: 446842401
Change-Id: Ic66c537d810dda858318a95e5f7b2242f58f7c75
diff --git a/absl/flags/BUILD b/absl/flags/BUILD
index c180599..b6e5343 100644
--- a/absl/flags/BUILD
+++ b/absl/flags/BUILD
@@ -13,7 +13,6 @@
         ":_flagvalues",
         ":_helpers",
         ":_validators",
-        "@six_archive//:six",
     ],
 )
 
@@ -31,7 +30,6 @@
     srcs_version = "PY2AND3",
     deps = [
         ":_helpers",
-        "@six_archive//:six",
     ],
 )
 
@@ -67,7 +65,6 @@
         ":_exceptions",
         ":_helpers",
         "//absl:_collections_abc",
-        "@six_archive//:six",
     ],
 )
 
@@ -80,7 +77,6 @@
         ":_flag",
         ":_helpers",
         ":_validators_classes",
-        "@six_archive//:six",
     ],
 )
 
@@ -88,7 +84,6 @@
     name = "_helpers",
     srcs = ["_helpers.py"],
     srcs_version = "PY2AND3",
-    deps = ["@six_archive//:six"],
 )
 
 py_library(
diff --git a/absl/flags/__init__.py b/absl/flags/__init__.py
index 99501bb..e6014a6 100644
--- a/absl/flags/__init__.py
+++ b/absl/flags/__init__.py
@@ -25,10 +25,6 @@
 and optionally type-converted, when it's seen on the command line.
 """
 
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
 import getopt
 import os
 import re
@@ -43,7 +39,6 @@
 from absl.flags import _flagvalues
 from absl.flags import _helpers
 from absl.flags import _validators
-import six
 
 # Initialize the FLAGS_MODULE as early as possible.
 # It's only used by adopt_module_key_flags to take SPECIAL_FLAGS into account.
diff --git a/absl/flags/_argument_parser.py b/absl/flags/_argument_parser.py
index 4f6bd69..9c6c8c6 100644
--- a/absl/flags/_argument_parser.py
+++ b/absl/flags/_argument_parser.py
@@ -18,22 +18,17 @@
 aliases defined at the package level instead.
 """
 
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
 import collections
 import csv
 import io
 import string
 
 from absl.flags import _helpers
-import six
 
 
 def _is_integer_type(instance):
   """Returns True if instance is an integer, and not a bool."""
-  return (isinstance(instance, six.integer_types) and
+  return (isinstance(instance, int) and
           not isinstance(instance, bool))
 
 
@@ -95,7 +90,7 @@
 #   inherit from `ArgumentParser` and not `ArgumentParser[SomeType]`.
 #   The corresponding DEFINE_someType method (the public API) can be annotated
 #   to return FlagHolder[SomeType].
-class ArgumentParser(six.with_metaclass(_ArgumentParserCache, object)):
+class ArgumentParser(metaclass=_ArgumentParserCache):
   """Base class used to parse and convert arguments.
 
   The parse() method checks to make sure that the string argument is a
@@ -128,7 +123,7 @@
     Returns:
       The parsed value in native type.
     """
-    if not isinstance(argument, six.string_types):
+    if not isinstance(argument, str):
       raise TypeError('flag value must be a string, found "{}"'.format(
           type(argument)))
     return argument
@@ -228,7 +223,7 @@
   def convert(self, argument):
     """Returns the float value of argument."""
     if (_is_integer_type(argument) or isinstance(argument, float) or
-        isinstance(argument, six.string_types)):
+        isinstance(argument, str)):
       return float(argument)
     else:
       raise TypeError(
@@ -274,7 +269,7 @@
     """Returns the int value of argument."""
     if _is_integer_type(argument):
       return argument
-    elif isinstance(argument, six.string_types):
+    elif isinstance(argument, str):
       base = 10
       if len(argument) > 2 and argument[0] == '0':
         if argument[1] == 'o':
@@ -296,14 +291,14 @@
 
   def parse(self, argument):
     """See base class."""
-    if isinstance(argument, six.string_types):
+    if isinstance(argument, str):
       if argument.lower() in ('true', 't', '1'):
         return True
       elif argument.lower() in ('false', 'f', '0'):
         return False
       else:
         raise ValueError('Non-boolean argument to boolean flag', argument)
-    elif isinstance(argument, six.integer_types):
+    elif isinstance(argument, int):
       # Only allow bool or integer 0, 1.
       # Note that float 1.0 == True, 0.0 == False.
       bool_value = bool(argument)
@@ -433,7 +428,7 @@
     """
     if isinstance(argument, self.enum_class):
       return argument
-    elif not isinstance(argument, six.string_types):
+    elif not isinstance(argument, str):
       raise ValueError(
           '{} is not an enum member or a name of a member in {}'.format(
               argument, self.enum_class))
@@ -496,18 +491,10 @@
 
   def serialize(self, value):
     """Serializes a list as a CSV string or unicode."""
-    if six.PY2:
-      # In Python2 csv.writer doesn't accept unicode, so we convert to UTF-8.
-      output = io.BytesIO()
-      writer = csv.writer(output, delimiter=self.list_sep)
-      writer.writerow([unicode(x).encode('utf-8') for x in value])  # pylint: disable=undefined-variable
-      serialized_value = output.getvalue().decode('utf-8').strip()
-    else:
-      # In Python3 csv.writer expects a text stream.
-      output = io.StringIO()
-      writer = csv.writer(output, delimiter=self.list_sep)
-      writer.writerow([str(x) for x in value])
-      serialized_value = output.getvalue().strip()
+    output = io.StringIO()
+    writer = csv.writer(output, delimiter=self.list_sep)
+    writer.writerow([str(x) for x in value])
+    serialized_value = output.getvalue().strip()
 
     # We need the returned value to be pure ascii or Unicodes so that
     # when the xml help is generated they are usefully encodable.
diff --git a/absl/flags/_flag.py b/absl/flags/_flag.py
index a1c53ff..2a1a0b1 100644
--- a/absl/flags/_flag.py
+++ b/absl/flags/_flag.py
@@ -18,10 +18,6 @@
 aliases defined at the package level instead.
 """
 
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
 import copy
 import functools
 
@@ -29,7 +25,6 @@
 from absl.flags import _argument_parser
 from absl.flags import _exceptions
 from absl.flags import _helpers
-import six
 
 
 @functools.total_ordering
@@ -411,7 +406,7 @@
 
   def _parse(self, arguments):
     if (isinstance(arguments, abc.Iterable) and
-        not isinstance(arguments, six.string_types)):
+        not isinstance(arguments, str)):
       arguments = list(arguments)
 
     if not isinstance(arguments, list):
diff --git a/absl/flags/_flag.pyi b/absl/flags/_flag.pyi
index f28bbf3..3c8d44a 100644
--- a/absl/flags/_flag.pyi
+++ b/absl/flags/_flag.pyi
@@ -20,7 +20,6 @@
 from absl._collections_abc import abc
 from absl.flags import _argument_parser
 import enum
-import six
 
 from typing import Text, TypeVar, Generic, Iterable, Type, List, Optional, Any, Union, Sequence
 
diff --git a/absl/flags/_flagvalues.py b/absl/flags/_flagvalues.py
index c9be720..443524c 100644
--- a/absl/flags/_flagvalues.py
+++ b/absl/flags/_flagvalues.py
@@ -17,10 +17,6 @@
 aliases defined at the package level instead.
 """
 
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
 import copy
 import itertools
 import logging
@@ -32,7 +28,6 @@
 from absl.flags import _flag
 from absl.flags import _helpers
 from absl.flags import _validators_classes
-import six
 
 # pylint: disable=unused-import
 try:
@@ -247,7 +242,7 @@
     for flags_by_module_dict in (self.flags_by_module_dict(),
                                  self.flags_by_module_id_dict(),
                                  self.key_flags_by_module_dict()):
-      for flags_in_module in six.itervalues(flags_by_module_dict):
+      for flags_in_module in flags_by_module_dict.values():
         # While (as opposed to if) takes care of multiple occurrences of a
         # flag in the list for the same module.
         while flag_obj in flags_in_module:
@@ -313,7 +308,7 @@
     registered_flag = self._flags().get(flagname)
     if registered_flag is None:
       return default
-    for module, flags in six.iteritems(self.flags_by_module_dict()):
+    for module, flags in self.flags_by_module_dict().items():
       for flag in flags:
         # It must compare the flag with the one in _flags. This is because a
         # flag might be overridden only for its long name (or short name),
@@ -338,7 +333,7 @@
     registered_flag = self._flags().get(flagname)
     if registered_flag is None:
       return default
-    for module_id, flags in six.iteritems(self.flags_by_module_id_dict()):
+    for module_id, flags in self.flags_by_module_id_dict().items():
       for flag in flags:
         # It must compare the flag with the one in _flags. This is because a
         # flag might be overridden only for its long name (or short name),
@@ -389,7 +384,7 @@
     Args:
       flag_values: FlagValues, the FlagValues instance from which to copy flags.
     """
-    for flag_name, flag in six.iteritems(flag_values._flags()):  # pylint: disable=protected-access
+    for flag_name, flag in flag_values._flags().items():  # pylint: disable=protected-access
       # Each flags with short_name appears here twice (once under its
       # normal name, and again with its short name).  To prevent
       # problems (DuplicateFlagError) with double flag registration, we
@@ -485,18 +480,8 @@
     if self.__dict__['__flags_parsed'] or fl[name].present:
       return fl[name].value
     else:
-      error_message = ('Trying to access flag --%s before flags were parsed.' %
-                       name)
-      if six.PY2:
-        # In Python 2, hasattr returns False if getattr raises any exception.
-        # That means if someone calls hasattr(FLAGS, 'flag'), it returns False
-        # instead of raises UnparsedFlagAccessError even if --flag is already
-        # defined. To make the error more visible, the best we can do is to
-        # log an error message before raising the exception.
-        # Don't log a full stacktrace here since that makes other callers
-        # get too much noise.
-        logging.error(error_message)
-      raise _exceptions.UnparsedFlagAccessError(error_message)
+      raise _exceptions.UnparsedFlagAccessError(
+          'Trying to access flag --%s before flags were parsed.' % name)
 
   def __setattr__(self, name, value):
     """Sets the 'value' attribute of the flag --name."""
@@ -507,7 +492,7 @@
     """Sets multiple flag values together, triggers validators afterwards."""
     fl = self._flags()
     known_flags = set()
-    for name, value in six.iteritems(attributes):
+    for name, value in attributes.items():
       if name in self.__dict__['__hiddenflags']:
         raise AttributeError(name)
       if name in fl:
@@ -528,7 +513,7 @@
           validator.
     """
     all_validators = set()
-    for flag in six.itervalues(self._flags()):
+    for flag in self._flags().values():
       all_validators.update(flag.validators)
     self._assert_validators(all_validators)
 
@@ -858,7 +843,7 @@
 
   def flag_values_dict(self):
     """Returns a dictionary that maps flag names to flag values."""
-    return {name: flag.value for name, flag in six.iteritems(self._flags())}
+    return {name: flag.value for name, flag in self._flags().items()}
 
   def __str__(self):
     """Returns a help string for all known flags."""
@@ -887,11 +872,10 @@
     else:
       output_lines = []
       # Just print one long list of flags.
-      values = six.itervalues(self._flags())
+      values = self._flags().values()
       if include_special_flags:
-        values = itertools.chain(values,
-                                 six.itervalues(
-                                     _helpers.SPECIAL_FLAGS._flags()))  # pylint: disable=protected-access
+        values = itertools.chain(
+            values, _helpers.SPECIAL_FLAGS._flags().values())  # pylint: disable=protected-access
       self._render_flag_list(values, output_lines, prefix)
       return '\n'.join(output_lines)
 
@@ -912,7 +896,7 @@
     if include_special_flags:
       self._render_module_flags(
           'absl.flags',
-          six.itervalues(_helpers.SPECIAL_FLAGS._flags()),  # pylint: disable=protected-access
+          _helpers.SPECIAL_FLAGS._flags().values(),  # pylint: disable=protected-access
           output_lines,
           prefix)
     return '\n'.join(output_lines)
@@ -1291,11 +1275,8 @@
                 is_key=is_key))
 
     outfile = outfile or sys.stdout
-    if six.PY2:
-      outfile.write(doc.toprettyxml(indent='  ', encoding='utf-8'))
-    else:
-      outfile.write(
-          doc.toprettyxml(indent='  ', encoding='utf-8').decode('utf-8'))
+    outfile.write(
+        doc.toprettyxml(indent='  ', encoding='utf-8').decode('utf-8'))
     outfile.flush()
 
   def _check_method_name_conflicts(self, name, flag):
diff --git a/absl/flags/_flagvalues.pyi b/absl/flags/_flagvalues.pyi
index 9f1e1a5..e25c6dd 100644
--- a/absl/flags/_flagvalues.pyi
+++ b/absl/flags/_flagvalues.pyi
@@ -16,7 +16,6 @@
 
 
 from absl.flags import _flag
-import six
 
 from typing import Any, Dict, Generic, Iterable, Iterator, List, Optional, Sequence, Text, Type, TypeVar
 
diff --git a/absl/flags/_helpers.py b/absl/flags/_helpers.py
index 68b8cfc..37ae360 100644
--- a/absl/flags/_helpers.py
+++ b/absl/flags/_helpers.py
@@ -34,9 +34,6 @@
 except ImportError:
   termios = None
 
-import six
-from six.moves import range  # pylint: disable=redefined-builtin
-
 
 _DEFAULT_HELP_WIDTH = 80  # Default width of help output.
 _MIN_HELP_WIDTH = 40  # Minimal "sane" width of help output. We assume that any
@@ -172,9 +169,6 @@
     An instance of minidom.Element.
   """
   s = str_or_unicode(value)
-  if six.PY2 and not isinstance(s, unicode):
-    # Get a valid unicode string.
-    s = s.decode('utf-8', 'ignore')
   if isinstance(value, bool):
     # Display boolean values as the C++ flag library does: no caps.
     s = s.lower()
@@ -340,7 +334,7 @@
   Yields:
     sequence of string suitable for a subprocess execution.
   """
-  for key, value in six.iteritems(flag_map):
+  for key, value in flag_map.items():
     if value is None:
       yield '--%s' % key
     elif isinstance(value, bool):