Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

run pyupgrade and optimize imports in pycharm #312

Merged
merged 5 commits into from
Jul 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 6 additions & 9 deletions example/backend/unstone/unstone.stoneg.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,13 @@
- Aliases are lost (they are expanded in-line)
- Docstrings are reformatted
"""
from __future__ import absolute_import, division, print_function, unicode_literals

import six

from stone.backend import CodeBackend
from stone.frontend.ast import AstTypeRef
from stone.ir import DataType
from stone.ir import List, String, Timestamp
from stone.ir import Struct, Union, Void
from stone.ir.data_types import _BoundedInteger, _BoundedFloat
from stone.backend import CodeBackend


class UnstoneBackend(CodeBackend):
Expand Down Expand Up @@ -50,7 +47,7 @@ def generate_data_type(self, data_type):
for field in data_type.fields:
type_repr = self.format_data_type(field.data_type)
if not field.has_default:
self.emit('%s %s' % (field.name, type_repr))
self.emit('{} {}'.format(field.name, type_repr))
else:
self.emit('%s %s = %s' %
(field.name, type_repr, self.format_value(field.default)))
Expand All @@ -74,7 +71,7 @@ def generate_data_type(self, data_type):
self.emit('%s' % (name))
else:
type_repr = self.format_data_type(field.data_type)
self.emit('%s %s' % (name, type_repr))
self.emit('{} {}'.format(name, type_repr))
if field.doc is not None:
with self.indent():
self.emit(self.format_value(field.doc))
Expand All @@ -86,7 +83,7 @@ def generate_data_type(self, data_type):
def generate_route(self, route):
"""Output a route definition."""
self.emit('')
self.emit('route %s (%s, %s, %s)' % (
self.emit('route {} ({}, {}, {})'.format(
route.name,
self.format_data_type(route.arg_data_type),
self.format_data_type(route.result_data_type),
Expand Down Expand Up @@ -136,10 +133,10 @@ def format_data_type(self, data_type):

def format_value(self, val):
"""Helper function to format a value."""
if isinstance(val, six.text_type):
if isinstance(val, str):
return self.format_string(val)
else:
return six.text_type(val)
return str(val)

def format_string(self, val):
"""Helper function to format a string."""
Expand Down
13 changes: 6 additions & 7 deletions ez_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,16 @@

This file can also be run as a script to install or upgrade setuptools.
"""
import contextlib
import optparse
import os
import platform
import shutil
import subprocess
import sys
import tempfile
import zipfile
import optparse
import subprocess
import platform
import textwrap
import contextlib

import zipfile
from distutils import log

try:
Expand Down Expand Up @@ -61,7 +60,7 @@ def _build_egg(egg, archive_filename, to_dir):
# returning the result
log.warn(egg)
if not os.path.exists(egg):
raise IOError('Could not build the egg.')
raise OSError('Could not build the egg.')


def get_zip_class():
Expand Down
1 change: 0 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# Don't import unicode_literals because of a bug in py2 setuptools
# where package_data is expected to be str and not unicode.
from __future__ import absolute_import, division, print_function

import sys

Expand Down
29 changes: 13 additions & 16 deletions stone/backend.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
from __future__ import absolute_import, division, print_function, unicode_literals

from abc import ABCMeta, abstractmethod
from contextlib import contextmanager
import argparse
import io
import logging
import os
import six
import textwrap
from abc import ABCMeta, abstractmethod
from contextlib import contextmanager

from stone.frontend.ir_generator import doc_ref_re
from stone.ir import (
Expand All @@ -21,7 +19,7 @@
import typing # pylint: disable=import-error,useless-suppression

# Generic Dict key-val types
DelimTuple = typing.Tuple[typing.Text, typing.Text]
DelimTuple = typing.Tuple[str, str]
K = typing.TypeVar('K')
V = typing.TypeVar('V')

Expand Down Expand Up @@ -67,8 +65,7 @@ def remove_aliases_from_api(api):
return api


@six.add_metaclass(ABCMeta)
class Backend(object):
class Backend(metaclass=ABCMeta):
"""
The parent class for all backends. All backends should extend this
class to be recognized as such.
Expand Down Expand Up @@ -214,7 +211,7 @@ def make_indent(self):

@contextmanager
def capture_emitted_output(self, output_buffer):
# type: (six.StringIO) -> typing.Iterator[None]
# type: (io.StringIO) -> typing.Iterator[None]
original_output = self.output
self.output = []
yield
Expand Down Expand Up @@ -245,11 +242,11 @@ def emit(self, s=''):
output buffer. If s is an empty string (default) then an empty line is
created with no indentation.
"""
assert isinstance(s, six.text_type), 's must be a unicode string'
assert isinstance(s, str), 's must be a unicode string'
assert '\n' not in s, \
'String to emit cannot contain newline strings.'
if s:
self.emit_raw('%s%s\n' % (self.make_indent(), s))
self.emit_raw('{}{}\n'.format(self.make_indent(), s))
else:
self.emit_raw('\n')

Expand Down Expand Up @@ -334,7 +331,7 @@ def process_doc(cls, doc, handler):
for you. The returned string will be substituted in the
docstring in place of the reference.
"""
assert isinstance(doc, six.text_type), \
assert isinstance(doc, str), \
'Expected string (unicode in PY2), got %r.' % type(doc)
cur_index = 0
parts = []
Expand Down Expand Up @@ -404,8 +401,8 @@ def generate_multiline_list(
skip_last_sep (bool): When compact is false, whether the last line
should have a trailing separator. Ignored when compact is true.
"""
assert len(delim) == 2 and isinstance(delim[0], six.text_type) and \
isinstance(delim[1], six.text_type), 'delim must be a tuple of two unicode strings.'
assert len(delim) == 2 and isinstance(delim[0], str) and \
isinstance(delim[1], str), 'delim must be a tuple of two unicode strings.'

if len(items) == 0:
self.emit(before + delim[0] + delim[1] + after)
Expand Down Expand Up @@ -475,8 +472,8 @@ def block(
http://en.wikipedia.org/wiki/Indent_style
"""
assert len(delim) == 2, 'delim must be a tuple of length 2'
assert (isinstance(delim[0], (six.text_type, type(None))) and
isinstance(delim[1], (six.text_type, type(None)))), (
assert (isinstance(delim[0], (str, type(None))) and
isinstance(delim[1], (str, type(None)))), (
'delim must be a tuple of two optional strings.')

if before and not allman:
Expand Down
2 changes: 0 additions & 2 deletions stone/backends/helpers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import absolute_import, division, print_function, unicode_literals

import re

_split_words_capitalization_re = re.compile(
Expand Down
4 changes: 1 addition & 3 deletions stone/backends/js_client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import absolute_import, division, print_function, unicode_literals

_MYPY = False
if _MYPY:
import typing # noqa: F401 # pylint: disable=import-error,unused-import,useless-suppression
Expand Down Expand Up @@ -113,7 +111,7 @@ def _generate_route(self, route_schema, namespace, route):

return_type = None
if self.args.wrap_response_in:
return_type = '%s<%s>' % (self.args.wrap_response_in,
return_type = '{}<{}>'.format(self.args.wrap_response_in,
fmt_type(route.result_data_type))
else:
return_type = fmt_type(route.result_data_type)
Expand Down
17 changes: 7 additions & 10 deletions stone/backends/js_helpers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from __future__ import absolute_import, division, print_function, unicode_literals

import json
import six

from stone.backends.helpers import (
fmt_camel,
fmt_pascal,
)
from stone.ir import (
Boolean,
Bytes,
Expand All @@ -20,10 +21,6 @@
is_struct_type,
is_user_defined_type,
)
from stone.backends.helpers import (
fmt_camel,
fmt_pascal,
)

_base_type_table = {
Boolean: 'boolean',
Expand All @@ -42,7 +39,7 @@


def fmt_obj(o):
if isinstance(o, six.text_type):
if isinstance(o, str):
# Prioritize single-quoted strings per JS style guides.
return repr(o).lstrip('u')
else:
Expand All @@ -53,7 +50,7 @@ def fmt_error_type(data_type, wrap_error_in=''):
"""
Converts the error type into a JSDoc type.
"""
return '%s.<%s>' % (
return '{}.<{}>'.format(
(wrap_error_in if (wrap_error_in != '') else 'Error'),
fmt_type(data_type)
)
Expand All @@ -65,7 +62,7 @@ def fmt_type_name(data_type):
(Does not attempt to enumerate subtypes.)
"""
if is_user_defined_type(data_type):
return fmt_pascal('%s%s' % (data_type.namespace.name, data_type.name))
return fmt_pascal('{}{}'.format(data_type.namespace.name, data_type.name))
else:
fmted_type = _base_type_table.get(data_type.__class__, 'Object')
if is_list_type(data_type):
Expand Down
33 changes: 15 additions & 18 deletions stone/backends/js_types.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,19 @@
from __future__ import absolute_import, division, print_function, unicode_literals

import json
import six
import sys

from stone.backend import CodeBackend
from stone.backends.js_helpers import (
fmt_jsdoc_union,
fmt_type,
fmt_type_name,
)
from stone.ir import (
is_user_defined_type,
is_union_type,
is_struct_type,
is_void_type,
unwrap,
)
from stone.backend import CodeBackend
from stone.backends.js_helpers import (
fmt_jsdoc_union,
fmt_type,
fmt_type_name,
)

_MYPY = False
if _MYPY:
Expand Down Expand Up @@ -94,7 +91,7 @@ def _parse_extra_args(self, api, extra_args_raw):
extra_args = {}

def die(m, extra_arg_raw):
print('Invalid --extra-arg:%s: %s' % (m, extra_arg_raw),
print('Invalid --extra-arg:{}: {}'.format(m, extra_arg_raw),
file=sys.stderr)
sys.exit(1)

Expand All @@ -110,20 +107,20 @@ def die(m, extra_arg_raw):
elif (not isinstance(extra_arg['match'], list) or
len(extra_arg['match']) != 2):
die('match key is not a list of two strings', extra_arg_raw)
elif (not isinstance(extra_arg['match'][0], six.text_type) or
not isinstance(extra_arg['match'][1], six.text_type)):
elif (not isinstance(extra_arg['match'][0], str) or
not isinstance(extra_arg['match'][1], str)):
print(type(extra_arg['match'][0]))
die('match values are not strings', extra_arg_raw)
elif 'arg_name' not in extra_arg:
die('No arg_name key', extra_arg_raw)
elif not isinstance(extra_arg['arg_name'], six.text_type):
elif not isinstance(extra_arg['arg_name'], str):
die('arg_name is not a string', extra_arg_raw)
elif 'arg_type' not in extra_arg:
die('No arg_type key', extra_arg_raw)
elif not isinstance(extra_arg['arg_type'], six.text_type):
elif not isinstance(extra_arg['arg_type'], str):
die('arg_type is not a string', extra_arg_raw)
elif ('arg_docstring' in extra_arg and
not isinstance(extra_arg['arg_docstring'], six.text_type)):
not isinstance(extra_arg['arg_docstring'], str)):
die('arg_docstring is not a string', extra_arg_raw)

attr_key, attr_val = extra_arg['match'][0], extra_arg['match'][1]
Expand Down Expand Up @@ -213,7 +210,7 @@ def _generate_struct(self, struct_type, extra_parameters=None, nameOverride=None
for param_name, param_type, param_docstring in extra_parameters:
param_docstring = ' - %s' % param_docstring if param_docstring else ''
self.emit_wrapped_text(
'@property {%s} [%s]%s' % (
'@property {{{}}} [{}]{}'.format(
param_type,
param_name,
param_docstring,
Expand All @@ -231,7 +228,7 @@ def _generate_struct(self, struct_type, extra_parameters=None, nameOverride=None
# Translate nullable types into optional properties.
field_name = '[' + field.name + ']' if nullable else field.name
self.emit_wrapped_text(
'@property {%s} %s%s' % (
'@property {{{}}} {}{}'.format(
field_js_type,
field_name,
self.process_doc(field_doc, self._docf),
Expand All @@ -258,7 +255,7 @@ def _generate_union(self, union_type):
if variant.doc:
variant_doc += ' ' + variant.doc
self.emit_wrapped_text(
'@property {%s} [%s]%s' % (
'@property {{{}}} [{}]{}'.format(
fmt_type(variant_data_type),
variant.name,
variant_doc,
Expand Down
14 changes: 6 additions & 8 deletions stone/backends/obj_c.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
from __future__ import absolute_import, division, print_function, unicode_literals

from contextlib import contextmanager

from stone.backend import CodeBackend
from stone.backends.obj_c_helpers import (
fmt_camel_upper,
fmt_class,
fmt_class_prefix,
fmt_import, )
from stone.ir import (
is_list_type,
is_map_type,
Expand All @@ -11,12 +15,6 @@
is_user_defined_type,
is_void_type,
unwrap_nullable, )
from stone.backend import CodeBackend
from stone.backends.obj_c_helpers import (
fmt_camel_upper,
fmt_class,
fmt_class_prefix,
fmt_import, )

stone_warning = """\
///
Expand Down