For Python 2, 3 compatibility.
484707
def compat_py2_py3():
    
    if (sys.version_info > (3, 0)):
        def iteritems(dictionary):
            return dictionary.items()

        def itervalues(dictionary):
            return dictionary.values()

    else:
        def iteritems(dictionary):
            return dictionary.iteritems()

        def itervalues(dictionary):
            return dictionary.itervalues()

    return iteritems, itervalues
162056
def universal_import(imports, imp_from=None, target=""):
    """"""
    importmap = []  # [((imp | old_imp, imp, version_check), imp_as), ...]
    for imps in imports:
        if len(imps) == 1:
            imp, imp_as = imps[0], imps[0]
        else:
            imp, imp_as = imps
        if imp_from is not None:
            imp = imp_from + "./" + imp  # marker for from ... import ...
        old_imp = None
        path = imp.split(".")
        for i in reversed(range(1, len(path) + 1)):
            base, exts = ".".join(path[:i]), path[i:]
            clean_base = base.replace("/", "")
            if clean_base in py3_to_py2_stdlib:
                old_imp, version_check = py3_to_py2_stdlib[clean_base]
                if exts:
                    old_imp += "."
                    if "/" in base and "/" not in old_imp:
                        old_imp += "/"  # marker for from ... import ...
                    old_imp += ".".join(exts)
                break
        if old_imp is None:
            paths = (imp,)
        elif not target:  # universal compatibility
            paths = (old_imp, imp, version_check)
        elif get_target_info_len2(target) >= version_check:  # if lowest is above, we can safely use new
            paths = (imp,)
        elif target.startswith("2"):  # "2" and "27" can safely use old
            paths = (old_imp,)
        elif get_target_info(target) < version_check:  # "3" should be compatible with all 3+
            paths = (old_imp, imp, version_check)
        else:  # "35" and above can safely use new
            paths = (imp,)
        importmap.append((paths, imp_as))

    stmts = []
    for paths, imp_as in importmap:
        if len(paths) == 1:
            more_stmts = single_import(paths[0], imp_as)
            stmts.extend(more_stmts)
        else:
            first, second, version_check = paths
            stmts.append("if _coconut_sys.version_info < " + str(version_check) + ":")
            first_stmts = single_import(first, imp_as)
            first_stmts[0] = openindent + first_stmts[0]
            first_stmts[-1] += closeindent
            stmts.extend(first_stmts)
            stmts.append("else:")
            second_stmts = single_import(second, imp_as)
            second_stmts[0] = openindent + second_stmts[0]
            second_stmts[-1] += closeindent
            stmts.extend(second_stmts)
    return "\n".join(stmts)
140737
def python(self, func, *args, **kwargs):
        """"""
        self.ops.append(lambda: func(*args, **kwargs))
1049560
def clean_requires_python(candidates):
    """"""
    all_candidates = []
    sys_version = ".".join(map(str, sys.version_info[:3]))
    from packaging.version import parse as parse_version

    py_version = parse_version(os.environ.get("PIP_PYTHON_VERSION", sys_version))
    for c in candidates:
        from_location = attrgetter("location.requires_python")
        requires_python = getattr(c, "requires_python", from_location(c))
        if requires_python:
            # Old specifications had people setting this to single digits
            # which is effectively the same as '>=digit,<digit+1'
            if requires_python.isdigit():
                requires_python = ">={0},<{1}".format(
                    requires_python, int(requires_python) + 1
                )
            try:
                specifierset = SpecifierSet(requires_python)
            except InvalidSpecifier:
                continue
            else:
                if not specifierset.contains(py_version):
                    continue
        all_candidates.append(c)
    return all_candidates
86040
def _py24_25_compat(self):
        
        if sys.version_info < (2, 6):
            # import_module() is used to avoid dep scanner.
            os_fork = import_module('mitogen.os_fork')
            mitogen.os_fork._notice_broker_or_pool(self)
929267
def main():
    """"""

    print("Python version %s" % sys.version)

    print("Testing compatibility for function defined with *args")
    test_func_args(func_old_args)
    test_func_args(func_new)

    print("Testing compatibility for function defined with **kwargs")
    test_func_kwargs(func_old_kwargs)
    test_func_kwargs(func_new)

    print("All tests successful - we can change *args and **kwargs to' \
          ' named args.")
    return 0
1049435
def python_2_unicode_compatible(klass):
    
    if sys.version_info[0] == 2:
        klass.__unicode__ = klass.__str__
        klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
    return klass
161393
def strtobytes(input, encoding):
    """"""
    py_version = sys.version_info[0]
    if py_version >= 3:
        return _strtobytes_py3(input, encoding)
    return _strtobytes_py2(input, encoding)
852218
def _recognize_basic_types(s):
    
    tps = [int, float]
    if not six.PY3:  # compat for older versions of six that don't have PY2
        tps.append(long)
    for tp in tps:
        try:
            return tp(s)
        except ValueError:
            pass
    if s.lower() == 'true':
        return True
    if s.lower() == 'false':
        return False
    if s.lower() in ['none', 'null']:
        return None

    return s
773831
def dict_unicodeize(some_dict):
    """"""

    # some python 2/3 compat
    if isinstance(some_dict, ("".__class__, u"".__class__)):
        if sys.version_info >= (3, 0):
            return some_dict

        return some_dict.decode('utf-8')
    elif isinstance(some_dict, collections.Mapping):
        return dict(map(dict_unicodeize, iteritems(some_dict)))
    elif isinstance(some_dict, collections.Iterable):
        return type(some_dict)(map(dict_unicodeize, some_dict))

    return some_dict
419380
def _CheckPythonVersionAndDisableWarnings(self):
    
    if self._checked_for_old_python_version:
      return
    if sys.version_info[0:3] < (2, 7, 9):
      logger.warning(
          'You are running a version of Python prior to 2.7.9. Your version '
          'of Python has multiple weaknesses in its SSL implementation that '
          'can allow an attacker to read or modify SSL encrypted data. '
          'Please update. Further SSL warnings will be suppressed. See '
          'https://www.python.org/dev/peps/pep-0466/ for more information.')

      # Some distributions de-vendor urllib3 from requests, so we have to
      # check if this has occurred and disable warnings in the correct
      # package.
      urllib3_module = urllib3
      if not urllib3_module:
        if hasattr(requests, 'packages'):
          urllib3_module = getattr(requests.packages, 'urllib3')

      if urllib3_module and hasattr(urllib3_module, 'disable_warnings'):
        urllib3_module.disable_warnings()

    self._checked_for_old_python_version = True
547457
def python(self):
        """"""
        py = vistir.compat.Path(self.base_paths["scripts"]).joinpath("python").absolute().as_posix()
        if not py:
            return vistir.compat.Path(sys.executable).as_posix()
        return py
1110282
def p_try_statement_3(self, p):
        """"""
        p[0] = self.asttypes.Try(statements=p[2], catch=p[3], fin=p[4])
        p[0].setpos(p)
629485
def _convert_to_3(path):  # pragma: no cover
    """"""
    try:
        log.warn('##### Trying to convert %s to Python 3. #####', path)
        subprocess.call(['2to3', '-w', path])
    except subprocess.SubprocessError:
        log.exception('Check if 2to3 is installed. https://docs.python.org/2/library/2to3.html')
        exit(1)
1218121
def is_python(self, path):
        """"""
        head, tail = os.path.splitext(path)
        return tail.lower() in (".py", ".pyw")
532259
def select_interpreter_for_targets(self, targets):
    """"""

    tgts_by_compatibilities, total_filter_set = self.partition_targets_by_compatibility(targets)
    allowed_interpreters = set(self.setup(filters=total_filter_set))

    # Constrain allowed_interpreters based on each target's compatibility requirements.
    for compatibility in tgts_by_compatibilities:
      compatible_with_target = set(self._matching(allowed_interpreters, compatibility))
      allowed_interpreters &= compatible_with_target

    if not allowed_interpreters:
      # Create a helpful error message.
      all_interpreter_version_strings = sorted({
        interpreter.version_string
        # NB: self.setup() requires filters to be passed, or else it will use the global interpreter
        # constraints. We allow any interpreter other than CPython 3.0-3.3, which is known to choke
        # with Pants.
        for interpreter in self.setup(filters=("CPython<3", "CPython>=3.3", "PyPy"))
      })
      unique_compatibilities = {tuple(c) for c in tgts_by_compatibilities.keys()}
      unique_compatibilities_strs = [','.join(x) for x in unique_compatibilities if x]
      tgts_by_compatibilities_strs = [t[0].address.spec for t in tgts_by_compatibilities.values()]
      raise self.UnsatisfiableInterpreterConstraintsError(dedent("""\
        Unable to detect a suitable interpreter for compatibilities: {} (Conflicting targets: {})

        Pants detected these interpreter versions on your system: {}

        Possible ways to fix this:
        * Modify your Python interpreter constraints by following https://www.pantsbuild.org/python_readme.html#configure-the-python-version.
        * Ensure the targeted Python version is installed and discoverable.
        * Modify Pants' interpreter search paths via --pants-setup-interpreter-search-paths.""".format(
          ' && '.join(sorted(unique_compatibilities_strs)),
          ', '.join(tgts_by_compatibilities_strs),
          ', '.join(all_interpreter_version_strings)
        )))
    # Return the lowest compatible interpreter.
    return min(allowed_interpreters)
976307
def str_on_2_unicode_on_3(s):
    

    if not PY3:
        return str(s)
    else:  # 3+
        if not isinstance(s, str):
            return str(s, encoding="utf-8")
        return s