How to use the yapf.yapflib.yapf_api.FormatCode function in yapf

To help you get started, we’ve selected a few yapf examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github tensorlayer / tensorlayer / tests / pending / test_yapf_format.py View on Github external
def test_files_format(self):

        for file in list_all_py_files():

            try:

                print(file)
                code = _read_utf_8_file(file)

                # https://pypi.python.org/pypi/yapf/0.20.2#example-as-a-module
                diff, changed = FormatCode(code, filename=file, style_config='setup.cfg', print_diff=True)

                if changed:
                    print(diff)
                    self.badly_formatted_files.append(file)
            except Exception as e:
                print("Error while processing file: `%s`\n" "Error: %s" % (file, str(e)))

        with self.assertNotRaises(Exception):

            str_err = ""

            if self.badly_formatted_files:
                for filename in self.badly_formatted_files:
                    str_err += 'yapf -i --style=setup.cfg %s\n' % filename

                str_err = "\n======================================================================================\n" \
github bdestombe / flopymetascript / flopymetascript / model.py View on Github external
initial_indent = ' ' * bonus_space

        k = self.parameters[name].keys()
        kwargs = ', '.join(map(''.join, zip(k, 500 * ['='], k)))

        prelude = name.split('.')[-1].lower() + ' = '
        prelude2 = initial_indent + \
                   prelude + \
                   self.packages[name]['class'].__module__ + '.' + \
                   self.packages[name]['class'].__name__ + \
                   '('

        s = prelude2 + kwargs + ')'

        if use_yapf:
            s2 = FormatCode(s, style_config=style)[0][:-1]

        else:
            sout = textwrap.wrap(
                s,
                width=width,
                initial_indent=' ' * bonus_space,
                subsequent_indent=' ' * (bonus_space + len(prelude2)),
                break_on_hyphens=False,
                break_long_words=False)
            s2 = '\n'.join(sout)

        return s2
github Xython / YAPyPy / kizmi / database / dbg_emit.py View on Github external
elif isinstance(each, (Python, Engine)):
            pass
        else:
            raise TypeError(type(each))

    ctx = Context('', tables, relations)
    proc = Proc([
        'from kizmi.database.types import *',
        'import kizmi.database.infrastructure as db',
        'import builtins',
    ])
    for each in asts:
        proc, ctx = emit(each, proc, ctx)
    proc += '__base__.metadata.create_all(bind=engine)'
    proc += 'session = __session__'
    return FormatCode(dedent(dumps(proc.codes)))[0]
github pignacio / vim-yapf-format / python / yapf_format.py View on Github external
def main():
    if not _YAPF_IMPORTED:
        return

    encoding = vim.eval('&encoding')
    buf = vim.current.buffer
    unicode_buf = [unicode(s, encoding) for s in buf]
    text = '\n'.join(unicode_buf)
    buf_range = (vim.current.range.start, vim.current.range.end)
    lines_range = [pos + 1 for pos in buf_range]
    style_config = _get_style()
    vim.command('let l:used_style = "{}"'.format(style_config))
    try:
        formatted = yapf_api.FormatCode(text,
                                        filename='',
                                        style_config=style_config,
                                        lines=[lines_range],
                                        verify=False)
    except (SyntaxError, IndentationError) as err:
        vim.command('let l:error_type = "{}"'.format(type(err).__name__))
        vim.command('let l:error_position = [{}, {}]'.format(err.lineno,
                                                             err.offset))
        return

    if isinstance(formatted, tuple):
        formatted = formatted[0]

    lines = formatted.rstrip('\n').split('\n')
    sequence = difflib.SequenceMatcher(None, unicode_buf, lines)
github caproto / caproto / caproto / server / conversion.py View on Github external
def _format(line, *, indent=0):
    '''Format Python code lines, with a specific indent

    NOTE: Uses yapf if available
    '''
    prefix = ' ' * indent
    if yapf is None:
        yield prefix + line
    else:
        from yapf.yapflib.yapf_api import FormatCode
        from yapf.yapflib.style import _style

        # TODO study awkward yapf api more closely
        _style['COLUMN_LIMIT'] = 79 - indent
        for formatted_line in FormatCode(line)[0].split('\n'):
            if formatted_line:
                yield prefix + formatted_line.rstrip()
github frostidaho / dynmen / utils / class_generator.py View on Github external
def format_code(source):
    import yapf
    from yapf.yapflib.yapf_api import FormatCode
    SetGlobalStyle = yapf.style.SetGlobalStyle
    cfg = yapf.style.CreatePEP8Style()
    cfg['ALLOW_MULTILINE_DICTIONARY_KEYS'] = True
    cfg['COLUMN_LIMIT'] = 90
    cfg['DEDENT_CLOSING_BRACKETS'] = True
    SetGlobalStyle(cfg)
    source, changed = FormatCode(source)
    return source
github google / yapf / yapf / __init__.py View on Github external
# the program by hand. 'raw_input' throws an EOFError exception if
        # 'Ctrl-D' is pressed, which makes it easy to bail out of this loop.
        original_source.append(py3compat.raw_input())
      except EOFError:
        break
      except KeyboardInterrupt:
        return 1

    if style_config is None and not args.no_local_style:
      style_config = file_resources.GetDefaultStyleForDir(os.getcwd())

    source = [line.rstrip() for line in original_source]
    source[0] = py3compat.removeBOM(source[0])

    try:
      reformatted_source, _ = yapf_api.FormatCode(
          py3compat.unicode('\n'.join(source) + '\n'),
          filename='',
          style_config=style_config,
          lines=lines,
          verify=args.verify)
    except tokenize.TokenError as e:
      raise errors.YapfError('%s:%s' % (e.args[1][0], e.args[0]))

    file_resources.WriteReformattedCode('', reformatted_source)
    return 0

  # Get additional exclude patterns from ignorefile
  exclude_patterns_from_ignore_file = file_resources.GetExcludePatternsForDir(
      os.getcwd())

  files = file_resources.GetCommandLineFiles(args.files, args.recursive,
github MolSSI / QCElemental / devtools / scripts / build_physical_constants_2014.py View on Github external
for pc in constants['constant']:
    value = pc['Value'].strip()
    uncertainty = pc['Uncertainty']
    if uncertainty == '(exact)':
        value = value.replace('...', '')

    constants_json["constants"][pc["Quantity "].lower()] = {
        "quantity": pc["Quantity "],
        "unit": pc["Unit"],
        "value": value.replace(" ", ""),
        'uncertainty': uncertainty
    }
output += "nist_{}_codata = {}".format(year, constants_json)

output = FormatCode(output)

fn = "nist_{}_codata.py".format(year)
with open(fn, "w") as handle:
    handle.write(output[0])
github statsmodels / statsmodels / tools / export_notebooks_to_python.py View on Github external
continue
                elif block.startswith('# In[ ]:'):
                    continue
                if block.startswith('#'):
                    # Wrap comments from Markdown
                    block = textwrap.fill(block, width=74)
                    block = block.replace('\n', '\n# ')
                code_out.append(block)
            if not code_out[0]:
                code_out = code_out[1:]
            loc = 0
            if 'coding' in code_out[0]:
                loc = 1
            code_out.insert(loc, DO_NOT_EDIT.format(notebook=nb_full_name))
            code_out = '\n'.join(code_out)
            code_out, success = FormatCode(code_out, style_config='pep8')
            with open(out_file, 'w') as of:
                of.write(code_out)
github bdestombe / flopymetascript / flopymetascript / parameter.py View on Github external
s = self.string[1:-1]

        elif key == 'dtype' and self.string[:15] == '(numpy.record, ':
            # dtype in most packages
            s = "np.dtype(" + self.string[15:]

        elif key == 'dtype' and self.string[:3] == "[('":
            # SSM dtype
            s = "np.dtype(" + self.string + ')'

        else:
            s = self.string

        if use_yapf:
            # the :-1 removes the extra \n which is added by yapf
            s3 = FormatCode(prelude + s, style_config=style)[0][:-1]

        else:
            if key == 'stress_period_data':
                s1 = self.print_string1(
                    s, prelude, width=width - 1, bonus_space=bonus_space)
                s1 = '\\\n'.join(s1)
            else:
                s1 = self.print_string1(
                    s, prelude, width=width, bonus_space=bonus_space)
                s1 = '\n'.join(s1)
            s3 = ' ' * bonus_space + prelude + s1[len(prelude) + bonus_space:]

        return s3