Fix flake8 errors and disable ignore case

below issures are removed from ignore cases:
    E114 indentation is not a multiple of four (comment)
    E116 unexpected indentation (comment)
    E121 continuation line under-indented for hanging indent
    E122 continuation line missing indentation or outdented
    E123 closing bracket does not match indentation of opening bracket's line
    E124 closing bracket does not match visual indentation
    E125 continuation line with same indent as next logical line
    E126 continuation line over-indented for hanging indent
    E127 continuation line over-indented for visual indent
    E128 continuation line under-indented for visual indent
    E129 visually indented line with same indent as next logical line
    E131 continuation line unaligned for hanging indent
    E201 whitespace after '('
    E228 missing whitespace around modulo operator
    E231 missing whitespace after ','
    E241 multiple spaces after ':'
    E251 unexpected spaces around keyword / parameter equals
    E265 block comment should start with '#'
    E271 multiple spaces after keyword
    E302 expected 2 blank lines, found 1
    E303 too many blank lines
    E305 expected 2 blank lines after class or function definition, found 1
    E704 multiple statements on one line (def)
    E713 test for membership should be 'not in'
    E714 test for object identity should be 'is not'
    E722 do not use bare except'
    E731 do not assign a lambda expression, use a def
    E999 SyntaxError: invalid syntax (this is likely python3)
    F401 <foo> imported but unused
    F841 local variable 'foo' is assigned to but never used
    H201: no 'except:'
    H233: Python 3.x incompatible use of print operator
    B001 Do not use bare `except:`
    B004 Using `hasattr(x, '__call__')` to test
         if `x` is callable is unreliable.
    B305 `.next()` is not a thing on Python 3. Use the `next()` builtin.
    B306 `BaseException.message` has been deprecated as of Python 2.6
          and is removed in Python 3.
    B007 Loop control variable 'key' not used within the loop body.
remain below issues in ignores:
    E402 module level import not at top of file
    ./service-mgmt-api/sm-api/sm_api/cmd/__init__.py:25

    Hxxx since which are related with document format

    F811 redefinition of unused '<foo>' from line <x>
    ./service-mgmt-tools/sm-tools/sm_tools/sm_configure.py:18

    F821 undefined name 'e'
    ./service-mgmt-api/sm-api/sm_api/common/utils.py:448

    B006 Do not use mutable data structures for argument defaults.
    ./service-mgmt-api/sm-api/sm_api/common/service.py:59

    B008 Do not perform calls in argument defaults.
    ./service-mgmt-api/sm-api/sm_api/openstack/common/timeutils.py:117

Test have been done:Build,Deploy,some smc command,such as smc service-list,
smc service-show, sm-dump, etc

Story: 2003430
Task: 26524

Change-Id: I3e2a4a31f87e3ff66cfce86f54285e830ee1c3dc
Signed-off-by: Sun Austin <austin.sun@intel.com>
This commit is contained in:
Sun Austin 2018-10-31 10:51:20 +08:00
parent fa29551d9e
commit da53f143ee
88 changed files with 354 additions and 356 deletions

View File

@ -69,6 +69,7 @@ class AdminAuthHook(hooks.PecanHook):
rejects the request otherwise. rejects the request otherwise.
""" """
def before(self, state): def before(self, state):
ctx = state.request.context ctx = state.request.context

View File

@ -64,4 +64,5 @@ def main():
print(e) print(e)
sys.exit(-4) sys.exit(-4)
main() main()

View File

@ -103,4 +103,5 @@ class Controller(rest.RestController):
def get(self): def get(self):
return Version1.convert() return Version1.convert()
__all__ = Controller __all__ = Controller

View File

@ -9,8 +9,6 @@
# All Rights Reserved. # All Rights Reserved.
# #
import datetime
import wsme import wsme
from wsme import types as wsme_types from wsme import types as wsme_types

View File

@ -4,8 +4,6 @@
# SPDX-License-Identifier: Apache-2.0 # SPDX-License-Identifier: Apache-2.0
# #
import json
import wsme
from wsme import types as wsme_types from wsme import types as wsme_types
import wsmeext.pecan as wsme_pecan import wsmeext.pecan as wsme_pecan
import pecan import pecan

View File

@ -4,8 +4,6 @@
# SPDX-License-Identifier: Apache-2.0 # SPDX-License-Identifier: Apache-2.0
# #
import json
import wsme
from wsme import types as wsme_types from wsme import types as wsme_types
import wsmeext.pecan as wsme_pecan import wsmeext.pecan as wsme_pecan
import pecan import pecan

View File

@ -33,7 +33,6 @@ import json
from sm_api.api.controllers.v1 import base from sm_api.api.controllers.v1 import base
from sm_api.api.controllers.v1 import smc_api from sm_api.api.controllers.v1 import smc_api
from sm_api.openstack.common import log from sm_api.openstack.common import log
from sm_api.api.controllers.v1 import services
LOG = log.getLogger(__name__) LOG = log.getLogger(__name__)
@ -226,7 +225,7 @@ class ServiceNodeController(rest.RestController):
# check whether hostname exists in nodes table # check whether hostname exists in nodes table
node_exists = False node_exists = False
sm_nodes = pecan.request.dbapi.sm_node_get_by_name(hostname) sm_nodes = pecan.request.dbapi.sm_node_get_by_name(hostname)
for sm_node in sm_nodes: for _sm_node in sm_nodes:
node_exists = True node_exists = True
return node_exists return node_exists
@ -613,7 +612,7 @@ class ServiceNodeController(rest.RestController):
try: try:
data = self._get_sm_node_state(hostname) data = self._get_sm_node_state(hostname)
except: except Exception as e:
LOG.exception("No entry in database for %s:" % hostname) LOG.exception("No entry in database for %s:" % hostname)
return ServiceNode(origin="sm", return ServiceNode(origin="sm",
hostname=hostname, hostname=hostname,

View File

@ -4,8 +4,6 @@
# SPDX-License-Identifier: Apache-2.0 # SPDX-License-Identifier: Apache-2.0
# #
import json
import wsme
from wsme import types as wsme_types from wsme import types as wsme_types
import wsmeext.pecan as wsme_pecan import wsmeext.pecan as wsme_pecan
import pecan import pecan

View File

@ -4,8 +4,6 @@
# SPDX-License-Identifier: Apache-2.0 # SPDX-License-Identifier: Apache-2.0
# #
import json
import wsme
from wsme import types as wsme_types from wsme import types as wsme_types
import wsmeext.pecan as wsme_pecan import wsmeext.pecan as wsme_pecan
import pecan import pecan

View File

@ -91,7 +91,7 @@ def sm_api_notify(sm_dict):
break break
else: else:
LOG.debug(_("sm-api mismatch seqno tx message: %s rx message: %s " % (sm_buf, sm_ack))) LOG.debug(_("sm-api mismatch seqno tx message: %s rx message: %s " % (sm_buf, sm_ack)))
except: except Exception as e:
LOG.exception(_("sm-api bad rx message: %s" % sm_ack)) LOG.exception(_("sm-api bad rx message: %s" % sm_ack))
except socket.error as e: except socket.error as e:
@ -128,7 +128,7 @@ def sm_api_notify(sm_dict):
'SM_API_MSG_NODE_OPER': sm_ack_list[SM_API_MSG_NODE_OPER_FIELD], 'SM_API_MSG_NODE_OPER': sm_ack_list[SM_API_MSG_NODE_OPER_FIELD],
'SM_API_MSG_NODE_AVAIL': sm_ack_list[SM_API_MSG_NODE_AVAIL_FIELD] 'SM_API_MSG_NODE_AVAIL': sm_ack_list[SM_API_MSG_NODE_AVAIL_FIELD]
} }
except: except Exception as e:
LOG.exception(_("sm-api ack message error: %s" % sm_ack)) LOG.exception(_("sm-api ack message error: %s" % sm_ack))
sm_ack_dict = { sm_ack_dict = {
'SM_API_MSG_TYPE': "unknown_set_node", 'SM_API_MSG_TYPE': "unknown_set_node",

View File

@ -8,7 +8,6 @@
Hooks Hooks
""" """
import sqlite3
from pecan import hooks from pecan import hooks
from sm_api.common import context from sm_api.common import context
@ -60,6 +59,7 @@ class ContextHook(hooks.PecanHook):
or admin substring. Otherwise it is set to False. or admin substring. Otherwise it is set to False.
""" """
def __init__(self, public_api_routes): def __init__(self, public_api_routes):
self.public_api_routes = public_api_routes self.public_api_routes = public_api_routes
super(ContextHook, self).__init__() super(ContextHook, self).__init__()

View File

@ -20,6 +20,7 @@ class AuthTokenMiddleware(auth_token.AuthProtocol):
for public routes in the API. for public routes in the API.
""" """
def __init__(self, app, conf, public_api_routes=[]): def __init__(self, app, conf, public_api_routes=[]):
self.smapi_app = app self.smapi_app = app
self.public_api_routes = set(public_api_routes) self.public_api_routes = set(public_api_routes)

View File

@ -38,6 +38,7 @@ LOG = log.getLogger(__name__)
class ParsableErrorMiddleware(object): class ParsableErrorMiddleware(object):
"""Replace error body with something the client can parse. """Replace error body with something the client can parse.
""" """
def __init__(self, app): def __init__(self, app):
self.app = app self.app = app

View File

@ -73,7 +73,7 @@ class ProcessExecutionError(IOError):
def _cleanse_dict(original): def _cleanse_dict(original):
"""Strip all admin_password, new_pass, rescue_pass keys from a dict.""" """Strip all admin_password, new_pass, rescue_pass keys from a dict."""
return dict((k, v) for k, v in original.items() if not "_pass" in k) return dict((k, v) for k, v in original.items() if "_pass" not in k)
def wrap_exception(notifier=None, publisher_id=None, event_type=None, def wrap_exception(notifier=None, publisher_id=None, event_type=None,

View File

@ -659,7 +659,7 @@ def notify_mtc_and_recv(mtc_address, mtc_port, idict):
try: try:
mtc_response_dict = json.loads(mtc_response) mtc_response_dict = json.loads(mtc_response)
LOG.warning("Mtc Response: %s" % mtc_response_dict) LOG.warning("Mtc Response: %s" % mtc_response_dict)
except: except Exception as e:
LOG.exception("Mtc Response Error: %s" % mtc_response) LOG.exception("Mtc Response Error: %s" % mtc_response)
pass pass

View File

@ -174,7 +174,6 @@ class Connection(object):
:param name: The name of the services. :param name: The name of the services.
""" """
@abc.abstractmethod @abc.abstractmethod
def sm_service_group_members_get_list(self, service_group_name): def sm_service_group_members_get_list(self, service_group_name):
"""Return service group members in a service group """Return service group members in a service group

View File

@ -31,7 +31,6 @@ from sm_api.common import utils
from sm_api.db import api from sm_api.db import api
from sm_api.db.sqlalchemy import models from sm_api.db.sqlalchemy import models
from sm_api import objects from sm_api import objects
from sm_api.openstack.common.db import exception as db_exc
from sm_api.openstack.common.db.sqlalchemy import session as db_session from sm_api.openstack.common.db.sqlalchemy import session as db_session
from sm_api.openstack.common.db.sqlalchemy import utils as db_utils from sm_api.openstack.common.db.sqlalchemy import utils as db_utils
from sm_api.openstack.common import log from sm_api.openstack.common import log
@ -170,7 +169,6 @@ class Connection(api.Connection):
def iservice_get_by_name(self, name): def iservice_get_by_name(self, name):
result = model_query(models.service, read_deleted="no").\ result = model_query(models.service, read_deleted="no").\
filter_by(name=name) filter_by(name=name)
# first() since want a list
if not result: if not result:
raise exception.NodeNotFound(node=name) raise exception.NodeNotFound(node=name)
@ -232,7 +230,6 @@ class Connection(api.Connection):
def sm_node_get_by_name(self, name): def sm_node_get_by_name(self, name):
result = model_query(models.sm_node, read_deleted="no").\ result = model_query(models.sm_node, read_deleted="no").\
filter_by(name=name) filter_by(name=name)
# first() since want a list
if not result: if not result:
raise exception.NodeNotFound(node=name) raise exception.NodeNotFound(node=name)
@ -270,7 +267,6 @@ class Connection(api.Connection):
return result return result
@objects.objectify(objects.service_group_member) @objects.objectify(objects.service_group_member)
def sm_service_group_members_get_list(self, service_group_name): def sm_service_group_members_get_list(self, service_group_name):
result = model_query(models.sm_service_group_member, result = model_query(models.sm_service_group_member,

View File

@ -9,9 +9,7 @@
# #
from sqlalchemy import Column, MetaData, String, Table, UniqueConstraint from sqlalchemy import Column, MetaData, String, Table, UniqueConstraint
from sqlalchemy import Boolean, Integer, Enum, Text, ForeignKey, DateTime from sqlalchemy import Integer, Text, ForeignKey, DateTime
from sqlalchemy import Index
from sqlalchemy.dialects import postgresql
ENGINE = 'InnoDB' ENGINE = 'InnoDB'
CHARSET = 'utf8' CHARSET = 'utf8'

View File

@ -29,9 +29,8 @@ import json
from six.moves.urllib.parse import urlparse from six.moves.urllib.parse import urlparse
from oslo_config import cfg from oslo_config import cfg
from sqlalchemy import Column, ForeignKey, Integer, Boolean from sqlalchemy import Column, ForeignKey, Integer
from sqlalchemy import Enum, UniqueConstraint, String from sqlalchemy import String
from sqlalchemy import Index
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.types import TypeDecorator, VARCHAR from sqlalchemy.types import TypeDecorator, VARCHAR

View File

@ -106,6 +106,7 @@ def remotable_classmethod(fn):
# "orphaned" and remotable methods cannot be called. # "orphaned" and remotable methods cannot be called.
def remotable(fn): def remotable(fn):
"""Decorator for remotable object methods.""" """Decorator for remotable object methods."""
def wrapper(self, *args, **kwargs): def wrapper(self, *args, **kwargs):
ctxt = self._context ctxt = self._context
try: try:
@ -337,7 +338,8 @@ class Sm_apiObject(object):
name in self.obj_extra_fields): name in self.obj_extra_fields):
yield name, getattr(self, name) yield name, getattr(self, name)
items = lambda self: list(self.items()) def items(self):
return list(self.items())
def __getitem__(self, name): def __getitem__(self, name):
"""For backwards-compatibility with dict-based objects. """For backwards-compatibility with dict-based objects.

View File

@ -12,6 +12,7 @@ from sm_api.db import api as db_api
from sm_api.objects import base from sm_api.objects import base
from sm_api.objects import utils from sm_api.objects import utils
class sm_node(base.Sm_apiObject): class sm_node(base.Sm_apiObject):
dbapi = db_api.get_instance() dbapi = db_api.get_instance()

View File

@ -105,6 +105,7 @@ def nested_object_or_none(objclass):
def dt_serializer(name): def dt_serializer(name):
"""Return a datetime serializer for a named attribute.""" """Return a datetime serializer for a named attribute."""
def serializer(self, name=name): def serializer(self, name=name):
if getattr(self, name) is not None: if getattr(self, name) is not None:
return timeutils.isotime(getattr(self, name)) return timeutils.isotime(getattr(self, name))

View File

@ -120,7 +120,7 @@ def _import_module(mod_str):
def _is_in_group(opt, group): def _is_in_group(opt, group):
"Check if opt is in group." "Check if opt is in group."
for key, value in group._opts.items(): for _key, value in group._opts.items():
if value['opt'] == opt: if value['opt'] == opt:
return True return True
return False return False
@ -132,7 +132,7 @@ def _guess_groups(opt, mod_obj):
return 'DEFAULT' return 'DEFAULT'
# what other groups is it in? # what other groups is it in?
for key, value in cfg.CONF.items(): for _key, value in cfg.CONF.items():
if isinstance(value, cfg.CONF.GroupAttr): if isinstance(value, cfg.CONF.GroupAttr):
if _is_in_group(opt, value._group): if _is_in_group(opt, value._group):
return value._group.name return value._group.name
@ -254,5 +254,6 @@ def main():
sys.exit(0) sys.exit(0)
generate(sys.argv[1:]) generate(sys.argv[1:])
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -100,7 +100,7 @@ class DBAPI(object):
def __getattr__(self, key): def __getattr__(self, key):
backend = self.__backend or self.__get_backend() backend = self.__backend or self.__get_backend()
attr = getattr(backend, key) attr = getattr(backend, key)
if not self.__use_tpool or not hasattr(attr, '__call__'): if not self.__use_tpool or not callable(attr):
return attr return attr
def tpool_wrapper(*args, **kwargs): def tpool_wrapper(*args, **kwargs):

View File

@ -25,6 +25,7 @@ from sm_api.openstack.common.gettextutils import _ # noqa
class DBError(Exception): class DBError(Exception):
"""Wraps an implementation specific exception.""" """Wraps an implementation specific exception."""
def __init__(self, inner_exception=None): def __init__(self, inner_exception=None):
self.inner_exception = inner_exception self.inner_exception = inner_exception
super(DBError, self).__init__(str(inner_exception)) super(DBError, self).__init__(str(inner_exception))
@ -32,6 +33,7 @@ class DBError(Exception):
class DBDuplicateEntry(DBError): class DBDuplicateEntry(DBError):
"""Wraps an implementation specific exception.""" """Wraps an implementation specific exception."""
def __init__(self, columns=[], inner_exception=None): def __init__(self, columns=[], inner_exception=None):
self.columns = columns self.columns = columns
super(DBDuplicateEntry, self).__init__(inner_exception) super(DBDuplicateEntry, self).__init__(inner_exception)
@ -49,6 +51,7 @@ class DBInvalidUnicodeParameter(Exception):
class DbMigrationError(DBError): class DbMigrationError(DBError):
"""Wraps migration specific exception.""" """Wraps migration specific exception."""
def __init__(self, message=None): def __init__(self, message=None):
super(DbMigrationError, self).__init__(str(message)) super(DbMigrationError, self).__init__(str(message))

View File

@ -246,7 +246,6 @@ Efficient use of soft deletes:
""" """
import os.path
import re import re
import time import time
@ -366,6 +365,7 @@ class SqliteForeignKeysListener(PoolListener):
so the foreign key constraints will be enabled here for every so the foreign key constraints will be enabled here for every
database connection database connection
""" """
def connect(self, dbapi_con, con_record): def connect(self, dbapi_con, con_record):
dbapi_con.execute('pragma foreign_keys=ON') dbapi_con.execute('pragma foreign_keys=ON')
@ -627,6 +627,7 @@ def create_engine(sql_connection, sqlite_fk=False):
class Query(sqlalchemy.orm.query.Query): class Query(sqlalchemy.orm.query.Query):
"""Subclass of sqlalchemy.query with soft_delete() method.""" """Subclass of sqlalchemy.query with soft_delete() method."""
def soft_delete(self, synchronize_session='evaluate'): def soft_delete(self, synchronize_session='evaluate'):
return self.update({'deleted': literal_column('id'), return self.update({'deleted': literal_column('id'),
'updated_at': literal_column('updated_at'), 'updated_at': literal_column('updated_at'),

View File

@ -19,7 +19,6 @@
# #
import contextlib import contextlib
import errno import errno
import os import os

View File

@ -19,7 +19,6 @@
# #
import errno import errno
import functools import functools
import os import os

View File

@ -367,8 +367,7 @@ def setup(product_name):
def set_defaults(logging_context_format_string): def set_defaults(logging_context_format_string):
cfg.set_defaults(log_opts, cfg.set_defaults(log_opts,
logging_context_format_string= logging_context_format_string=logging_context_format_string)
logging_context_format_string)
def _find_facility_from_conf(): def _find_facility_from_conf():
@ -452,6 +451,7 @@ def _setup_logging_from_conf():
logger = logging.getLogger(mod) logger = logging.getLogger(mod)
logger.setLevel(level) logger.setLevel(level)
_loggers = {} _loggers = {}

View File

@ -17,7 +17,6 @@
# #
def notify(_context, message): def notify(_context, message):
"""Notifies the recipient of the desired event given the model""" """Notifies the recipient of the desired event given the model"""
pass pass

View File

@ -17,7 +17,6 @@
# #
NOTIFICATIONS = [] NOTIFICATIONS = []

View File

@ -470,7 +470,7 @@ def _parse_tokenize(rule):
# Handle leading parens on the token # Handle leading parens on the token
clean = tok.lstrip('(') clean = tok.lstrip('(')
for i in range(len(tok) - len(clean)): for _i in range(len(tok) - len(clean)):
yield '(', '(' yield '(', '('
# If it was only parentheses, continue # If it was only parentheses, continue
@ -498,7 +498,7 @@ def _parse_tokenize(rule):
yield 'check', _parse_check(clean) yield 'check', _parse_check(clean)
# Yield the trailing parens # Yield the trailing parens
for i in range(trail): for _i in range(trail):
yield ')', ')' yield ')', ')'

View File

@ -90,7 +90,7 @@ def main():
rawconfig.read(configfile) rawconfig.read(configfile)
config = wrapper.RootwrapConfig(rawconfig) config = wrapper.RootwrapConfig(rawconfig)
except ValueError as exc: except ValueError as exc:
msg = "Incorrect value in %s: %s" % (configfile, exc.message) msg = "Incorrect value in %s: %s" % (configfile, str(exc))
_exit_error(execname, msg, RC_BADCONFIG, log=False) _exit_error(execname, msg, RC_BADCONFIG, log=False)
except configparser.Error: except configparser.Error:
_exit_error(execname, "Incorrect configuration file: %s" % configfile, _exit_error(execname, "Incorrect configuration file: %s" % configfile,

View File

@ -105,7 +105,7 @@ class PathFilter(CommandFilter):
""" """
def match(self, userargs): def match(self, userargs):
command, arguments = userargs[0], userargs[1:] arguments = userargs[1:]
equal_args_num = len(self.args) == len(arguments) equal_args_num = len(self.args) == len(arguments)
exec_is_valid = super(PathFilter, self).match(userargs) exec_is_valid = super(PathFilter, self).match(userargs)

View File

@ -19,7 +19,6 @@
# #
from six.moves import configparser from six.moves import configparser
import logging import logging
import logging.handlers import logging.handlers
@ -39,6 +38,7 @@ class FilterMatchNotExecutable(Exception):
This exception is raised when a filter matched but no executable was This exception is raised when a filter matched but no executable was
found. found.
""" """
def __init__(self, match=None, **kwargs): def __init__(self, match=None, **kwargs):
self.match = match self.match = match

View File

@ -66,6 +66,7 @@ LOG = logging.getLogger(__name__)
class Pool(pools.Pool): class Pool(pools.Pool):
"""Class that implements a Pool of Connections.""" """Class that implements a Pool of Connections."""
def __init__(self, conf, connection_cls, *args, **kwargs): def __init__(self, conf, connection_cls, *args, **kwargs):
self.connection_cls = connection_cls self.connection_cls = connection_cls
self.conf = conf self.conf = conf
@ -188,6 +189,7 @@ class ConnectionContext(rpc_common.Connection):
class ReplyProxy(ConnectionContext): class ReplyProxy(ConnectionContext):
""" Connection class for RPC replies / callbacks """ """ Connection class for RPC replies / callbacks """
def __init__(self, conf, connection_pool): def __init__(self, conf, connection_pool):
self._call_waiters = {} self._call_waiters = {}
self._num_call_waiters = 0 self._num_call_waiters = 0
@ -257,6 +259,7 @@ def msg_reply(conf, msg_id, reply_q, connection_pool, reply=None,
class RpcContext(rpc_common.CommonRpcContext): class RpcContext(rpc_common.CommonRpcContext):
"""Context that supports replying to a rpc.call""" """Context that supports replying to a rpc.call"""
def __init__(self, **kwargs): def __init__(self, **kwargs):
self.msg_id = kwargs.pop('msg_id', None) self.msg_id = kwargs.pop('msg_id', None)
self.reply_q = kwargs.pop('reply_q', None) self.reply_q = kwargs.pop('reply_q', None)

View File

@ -173,6 +173,7 @@ class Connection(object):
An instance of this class should never be created by users of the rpc API. An instance of this class should never be created by users of the rpc API.
Use rpc.create_connection() instead. Use rpc.create_connection() instead.
""" """
def close(self): def close(self):
"""Close the connection. """Close the connection.
@ -354,7 +355,9 @@ def deserialize_remote_exception(conf, data):
return RemoteError(name, failure.get('message'), trace) return RemoteError(name, failure.get('message'), trace)
ex_type = type(failure) ex_type = type(failure)
str_override = lambda self: message
def str_override(self):
return message
new_ex_type = type(ex_type.__name__ + "_Remote", (ex_type,), new_ex_type = type(ex_type.__name__ + "_Remote", (ex_type,),
{'__str__': str_override, '__unicode__': str_override}) {'__str__': str_override, '__unicode__': str_override})
try: try:
@ -422,6 +425,7 @@ class ClientException(Exception):
hit by an RPC proxy object. Merely instantiating it records the hit by an RPC proxy object. Merely instantiating it records the
current exception information, which will be passed back to the current exception information, which will be passed back to the
RPC client without exceptional logging.""" RPC client without exceptional logging."""
def __init__(self): def __init__(self):
self._exc_info = sys.exc_info() self._exc_info = sys.exc_info()

View File

@ -322,6 +322,7 @@ class Publisher(object):
class DirectPublisher(Publisher): class DirectPublisher(Publisher):
"""Publisher class for 'direct'""" """Publisher class for 'direct'"""
def __init__(self, conf, channel, msg_id, **kwargs): def __init__(self, conf, channel, msg_id, **kwargs):
"""init a 'direct' publisher. """init a 'direct' publisher.
@ -338,6 +339,7 @@ class DirectPublisher(Publisher):
class TopicPublisher(Publisher): class TopicPublisher(Publisher):
"""Publisher class for 'topic'""" """Publisher class for 'topic'"""
def __init__(self, conf, channel, topic, **kwargs): def __init__(self, conf, channel, topic, **kwargs):
"""init a 'topic' publisher. """init a 'topic' publisher.
@ -357,6 +359,7 @@ class TopicPublisher(Publisher):
class FanoutPublisher(Publisher): class FanoutPublisher(Publisher):
"""Publisher class for 'fanout'""" """Publisher class for 'fanout'"""
def __init__(self, conf, channel, topic, **kwargs): def __init__(self, conf, channel, topic, **kwargs):
"""init a 'fanout' publisher. """init a 'fanout' publisher.

View File

@ -239,6 +239,7 @@ class Publisher(object):
class DirectPublisher(Publisher): class DirectPublisher(Publisher):
"""Publisher class for 'direct'""" """Publisher class for 'direct'"""
def __init__(self, conf, session, msg_id): def __init__(self, conf, session, msg_id):
"""Init a 'direct' publisher.""" """Init a 'direct' publisher."""
super(DirectPublisher, self).__init__(session, msg_id, super(DirectPublisher, self).__init__(session, msg_id,
@ -247,6 +248,7 @@ class DirectPublisher(Publisher):
class TopicPublisher(Publisher): class TopicPublisher(Publisher):
"""Publisher class for 'topic'""" """Publisher class for 'topic'"""
def __init__(self, conf, session, topic): def __init__(self, conf, session, topic):
"""init a 'topic' publisher. """init a 'topic' publisher.
""" """
@ -257,6 +259,7 @@ class TopicPublisher(Publisher):
class FanoutPublisher(Publisher): class FanoutPublisher(Publisher):
"""Publisher class for 'fanout'""" """Publisher class for 'fanout'"""
def __init__(self, conf, session, topic): def __init__(self, conf, session, topic):
"""init a 'fanout' publisher. """init a 'fanout' publisher.
""" """
@ -267,6 +270,7 @@ class FanoutPublisher(Publisher):
class NotifyPublisher(Publisher): class NotifyPublisher(Publisher):
"""Publisher class for notifications""" """Publisher class for notifications"""
def __init__(self, conf, session, topic): def __init__(self, conf, session, topic):
"""init a 'topic' publisher. """init a 'topic' publisher.
""" """

View File

@ -242,6 +242,7 @@ class ZmqClient(object):
class RpcContext(rpc_common.CommonRpcContext): class RpcContext(rpc_common.CommonRpcContext):
"""Context that supports replying to a rpc.call.""" """Context that supports replying to a rpc.call."""
def __init__(self, **kwargs): def __init__(self, **kwargs):
self.replies = [] self.replies = []
super(RpcContext, self).__init__(**kwargs) super(RpcContext, self).__init__(**kwargs)

View File

@ -56,6 +56,7 @@ class Exchange(object):
Implements lookups. Implements lookups.
Subclass this to support hashtables, dns, etc. Subclass this to support hashtables, dns, etc.
""" """
def __init__(self): def __init__(self):
pass pass
@ -67,6 +68,7 @@ class Binding(object):
""" """
A binding on which to perform a lookup. A binding on which to perform a lookup.
""" """
def __init__(self): def __init__(self):
pass pass
@ -80,6 +82,7 @@ class MatchMakerBase(object):
Build off HeartbeatMatchMakerBase if building a Build off HeartbeatMatchMakerBase if building a
heartbeat-capable MatchMaker. heartbeat-capable MatchMaker.
""" """
def __init__(self): def __init__(self):
# Array of tuples. Index [2] toggles negation, [3] is last-if-true # Array of tuples. Index [2] toggles negation, [3] is last-if-true
self.bindings = [] self.bindings = []
@ -155,7 +158,7 @@ class MatchMakerBase(object):
# bit is for negate bindings - if we choose to implement it. # bit is for negate bindings - if we choose to implement it.
# last stops processing rules if this matches. # last stops processing rules if this matches.
for (binding, exchange, bit, last) in self.bindings: for (binding, exchange, _bit, last) in self.bindings:
if binding.test(key): if binding.test(key):
workers.extend(exchange.run(key)) workers.extend(exchange.run(key))
@ -171,6 +174,7 @@ class HeartbeatMatchMakerBase(MatchMakerBase):
Provides common methods for registering, Provides common methods for registering,
unregistering, and maintaining heartbeats. unregistering, and maintaining heartbeats.
""" """
def __init__(self): def __init__(self):
self.hosts = set() self.hosts = set()
self._heart = None self._heart = None
@ -269,6 +273,7 @@ class DirectBinding(Binding):
Although dots are used in the key, the behavior here is Although dots are used in the key, the behavior here is
that it maps directly to a host, thus direct. that it maps directly to a host, thus direct.
""" """
def test(self, key): def test(self, key):
if '.' in key: if '.' in key:
return True return True
@ -283,6 +288,7 @@ class TopicBinding(Binding):
that of a topic exchange (whereas where there are dots, behavior that of a topic exchange (whereas where there are dots, behavior
matches that of a direct exchange. matches that of a direct exchange.
""" """
def test(self, key): def test(self, key):
if '.' not in key: if '.' not in key:
return True return True
@ -291,6 +297,7 @@ class TopicBinding(Binding):
class FanoutBinding(Binding): class FanoutBinding(Binding):
"""Match on fanout keys, where key starts with 'fanout.' string.""" """Match on fanout keys, where key starts with 'fanout.' string."""
def test(self, key): def test(self, key):
if key.startswith('fanout~'): if key.startswith('fanout~'):
return True return True
@ -299,12 +306,14 @@ class FanoutBinding(Binding):
class StubExchange(Exchange): class StubExchange(Exchange):
"""Exchange that does nothing.""" """Exchange that does nothing."""
def run(self, key): def run(self, key):
return [(key, None)] return [(key, None)]
class LocalhostExchange(Exchange): class LocalhostExchange(Exchange):
"""Exchange where all direct topics are local.""" """Exchange where all direct topics are local."""
def __init__(self, host='localhost'): def __init__(self, host='localhost'):
self.host = host self.host = host
super(Exchange, self).__init__() super(Exchange, self).__init__()
@ -318,6 +327,7 @@ class DirectExchange(Exchange):
Exchange where all topic keys are split, sending to second half. Exchange where all topic keys are split, sending to second half.
i.e. "compute.host" sends a message to "compute.host" running on "host" i.e. "compute.host" sends a message to "compute.host" running on "host"
""" """
def __init__(self): def __init__(self):
super(Exchange, self).__init__() super(Exchange, self).__init__()
@ -331,6 +341,7 @@ class MatchMakerLocalhost(MatchMakerBase):
Match Maker where all bare topics resolve to localhost. Match Maker where all bare topics resolve to localhost.
Useful for testing. Useful for testing.
""" """
def __init__(self, host='localhost'): def __init__(self, host='localhost'):
super(MatchMakerLocalhost, self).__init__() super(MatchMakerLocalhost, self).__init__()
self.add_binding(FanoutBinding(), LocalhostExchange(host)) self.add_binding(FanoutBinding(), LocalhostExchange(host))
@ -344,6 +355,7 @@ class MatchMakerStub(MatchMakerBase):
Useful for testing, or for AMQP/brokered queues. Useful for testing, or for AMQP/brokered queues.
Will not work where knowledge of hosts is known (i.e. zeromq) Will not work where knowledge of hosts is known (i.e. zeromq)
""" """
def __init__(self): def __init__(self):
super(MatchMakerLocalhost, self).__init__() super(MatchMakerLocalhost, self).__init__()

View File

@ -63,6 +63,7 @@ class RedisTopicExchange(RedisExchange):
Exchange where all topic keys are split, sending to second half. Exchange where all topic keys are split, sending to second half.
i.e. "compute.host" sends a message to "compute" running on "host" i.e. "compute.host" sends a message to "compute" running on "host"
""" """
def run(self, topic): def run(self, topic):
while True: while True:
member_name = self.redis.srandmember(topic) member_name = self.redis.srandmember(topic)
@ -84,6 +85,7 @@ class RedisFanoutExchange(RedisExchange):
""" """
Return a list of all hosts. Return a list of all hosts.
""" """
def run(self, topic): def run(self, topic):
topic = topic.split('~', 1)[1] topic = topic.split('~', 1)[1]
hosts = self.redis.smembers(topic) hosts = self.redis.smembers(topic)
@ -97,6 +99,7 @@ class MatchMakerRedis(mm_common.HeartbeatMatchMakerBase):
""" """
MatchMaker registering and looking-up hosts with a Redis server. MatchMaker registering and looking-up hosts with a Redis server.
""" """
def __init__(self): def __init__(self):
super(MatchMakerRedis, self).__init__() super(MatchMakerRedis, self).__init__()

View File

@ -54,6 +54,7 @@ class RingExchange(mm.Exchange):
__init__ takes optional ring dictionary argument, otherwise __init__ takes optional ring dictionary argument, otherwise
loads the ringfile from CONF.mathcmaker_ringfile. loads the ringfile from CONF.mathcmaker_ringfile.
""" """
def __init__(self, ring=None): def __init__(self, ring=None):
super(RingExchange, self).__init__() super(RingExchange, self).__init__()
@ -76,6 +77,7 @@ class RingExchange(mm.Exchange):
class RoundRobinRingExchange(RingExchange): class RoundRobinRingExchange(RingExchange):
"""A Topic Exchange based on a hashmap.""" """A Topic Exchange based on a hashmap."""
def __init__(self, ring=None): def __init__(self, ring=None):
super(RoundRobinRingExchange, self).__init__(ring) super(RoundRobinRingExchange, self).__init__(ring)
@ -92,6 +94,7 @@ class RoundRobinRingExchange(RingExchange):
class FanoutRingExchange(RingExchange): class FanoutRingExchange(RingExchange):
"""Fanout Exchange based on a hashmap.""" """Fanout Exchange based on a hashmap."""
def __init__(self, ring=None): def __init__(self, ring=None):
super(FanoutRingExchange, self).__init__(ring) super(FanoutRingExchange, self).__init__(ring)
@ -111,6 +114,7 @@ class MatchMakerRing(mm.MatchMakerBase):
""" """
Match Maker where hosts are loaded from a static hashmap. Match Maker where hosts are loaded from a static hashmap.
""" """
def __init__(self, ring=None): def __init__(self, ring=None):
super(MatchMakerRing, self).__init__() super(MatchMakerRing, self).__init__()
self.add_binding(mm.FanoutBinding(), FanoutRingExchange(ring)) self.add_binding(mm.FanoutBinding(), FanoutRingExchange(ring))

View File

@ -35,6 +35,7 @@ class Service(service.Service):
"""Service object for binaries running on hosts. """Service object for binaries running on hosts.
A service enables rpc by listening to queues based on topic and host.""" A service enables rpc by listening to queues based on topic and host."""
def __init__(self, host, topic, manager=None, serializer=None): def __init__(self, host, topic, manager=None, serializer=None):
super(Service, self).__init__() super(Service, self).__init__()
self.host = host self.host = host

View File

@ -42,6 +42,7 @@ class Thread(object):
:class:`ThreadGroup`. The Thread will notify the :class:`ThreadGroup` when :class:`ThreadGroup`. The Thread will notify the :class:`ThreadGroup` when
it has done so it can be removed from the threads list. it has done so it can be removed from the threads list.
""" """
def __init__(self, thread, group): def __init__(self, thread, group):
self.thread = thread self.thread = thread
self.thread.link(_thread_done, group=group, thread=self) self.thread.link(_thread_done, group=group, thread=self)
@ -60,6 +61,7 @@ class ThreadGroup(object):
when need be). when need be).
* provide an easy API to add timers. * provide an easy API to add timers.
""" """
def __init__(self, thread_pool_size=10): def __init__(self, thread_pool_size=10):
self.pool = greenpool.GreenPool(thread_pool_size) self.pool = greenpool.GreenPool(thread_pool_size)
self.threads = [] self.threads = []

View File

@ -52,9 +52,9 @@ def parse_isotime(timestr):
try: try:
return iso8601.parse_date(timestr) return iso8601.parse_date(timestr)
except iso8601.ParseError as e: except iso8601.ParseError as e:
raise ValueError(e.message) raise ValueError(str(e))
except TypeError as e: except TypeError as e:
raise ValueError(e.message) raise ValueError(str(e))
def strtime(at=None, fmt=PERFECT_TIME_FORMAT): def strtime(at=None, fmt=PERFECT_TIME_FORMAT):
@ -124,7 +124,7 @@ def set_time_override(override_time=datetime.datetime.utcnow()):
def advance_time_delta(timedelta): def advance_time_delta(timedelta):
"""Advance overridden time using a datetime.timedelta.""" """Advance overridden time using a datetime.timedelta."""
assert(not utcnow.override_time is None) assert(utcnow.override_time is not None)
try: try:
for dt in utcnow.override_time: for dt in utcnow.override_time:
dt += timedelta dt += timedelta

View File

@ -8,6 +8,7 @@
from sm_client.common import utils from sm_client.common import utils
from keystoneclient.v3 import client as ksclient from keystoneclient.v3 import client as ksclient
def _get_ksclient(**kwargs): def _get_ksclient(**kwargs):
"""Get an endpoint and auth token from Keystone. """Get an endpoint and auth token from Keystone.

View File

@ -92,6 +92,7 @@ class Resource(object):
:param info: dictionary representing resource attributes :param info: dictionary representing resource attributes
:param loaded: prevent lazy-loading if set to True :param loaded: prevent lazy-loading if set to True
""" """
def __init__(self, manager, info, loaded=False): def __init__(self, manager, info, loaded=False):
self.manager = manager self.manager = manager
self._info = info self._info = info

View File

@ -17,6 +17,7 @@
# #
from __future__ import print_function
import argparse import argparse
import os import os
import sys import sys
@ -98,7 +99,7 @@ def print_list(objs, fields, field_labels, formatters={}, sortby=0):
data = getattr(o, field, '') data = getattr(o, field, '')
row.append(data) row.append(data)
pt.add_row(row) pt.add_row(row)
print pt.get_string(sortby=field_labels[sortby]) print(pt.get_string(sortby=field_labels[sortby]))
def print_tuple_list(tuples, tuple_labels=[]): def print_tuple_list(tuples, tuple_labels=[]):
@ -115,7 +116,7 @@ def print_tuple_list(tuples, tuple_labels=[]):
if len(t) == 2: if len(t) == 2:
pt.add_row([l, t[1]]) pt.add_row([l, t[1]])
print pt.get_string() print(pt.get_string())
def print_mapping(data, fields, dict_property="Property", wrap=0): def print_mapping(data, fields, dict_property="Property", wrap=0):
@ -142,7 +143,8 @@ def print_mapping(data, fields, dict_property="Property", wrap=0):
col1 = '' col1 = ''
else: else:
pt.add_row([k, v]) pt.add_row([k, v])
print pt.get_string() print(pt.get_string())
def print_dict(d, fields, dict_property="Property", wrap=0): def print_dict(d, fields, dict_property="Property", wrap=0):
pt = prettytable.PrettyTable([dict_property, 'Value'], pt = prettytable.PrettyTable([dict_property, 'Value'],
@ -169,7 +171,7 @@ def print_dict(d, fields, dict_property="Property", wrap=0):
col1 = '' col1 = ''
else: else:
pt.add_row([k, v]) pt.add_row([k, v])
print pt.get_string() print(pt.get_string())
def find_resource(manager, name_or_id): def find_resource(manager, name_or_id):
@ -258,5 +260,5 @@ def args_array_to_patch(op, attributes):
def exit(msg=''): def exit(msg=''):
if msg: if msg:
print >> sys.stderr, msg print(msg, file=sys.stderr)
sys.exit(1) sys.exit(1)

View File

@ -10,6 +10,7 @@ import sys
class BaseException(Exception): class BaseException(Exception):
"""An error occurred.""" """An error occurred."""
def __init__(self, message=None): def __init__(self, message=None):
self.message = message self.message = message
@ -164,6 +165,7 @@ class AmbiguousAuthSystem(ClientException):
"""Could not obtain token and endpoint using provided credentials.""" """Could not obtain token and endpoint using provided credentials."""
pass pass
# Alias for backwards compatibility # Alias for backwards compatibility
AmbigiousAuthSystem = AmbiguousAuthSystem AmbigiousAuthSystem = AmbiguousAuthSystem

View File

@ -120,7 +120,7 @@ def _import_module(mod_str):
def _is_in_group(opt, group): def _is_in_group(opt, group):
"Check if opt is in group." "Check if opt is in group."
for key, value in group._opts.items(): for _key, value in group._opts.items():
if value['opt'] == opt: if value['opt'] == opt:
return True return True
return False return False
@ -132,7 +132,7 @@ def _guess_groups(opt, mod_obj):
return 'DEFAULT' return 'DEFAULT'
# what other groups is it in? # what other groups is it in?
for key, value in cfg.CONF.items(): for _key, value in cfg.CONF.items():
if isinstance(value, cfg.CONF.GroupAttr): if isinstance(value, cfg.CONF.GroupAttr):
if _is_in_group(opt, value._group): if _is_in_group(opt, value._group):
return value._group.name return value._group.name
@ -254,5 +254,6 @@ def main():
sys.exit(0) sys.exit(0)
generate(sys.argv[1:]) generate(sys.argv[1:])
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -79,7 +79,7 @@ def main():
rawconfig.read(configfile) rawconfig.read(configfile)
config = wrapper.RootwrapConfig(rawconfig) config = wrapper.RootwrapConfig(rawconfig)
except ValueError as exc: except ValueError as exc:
msg = "Incorrect value in %s: %s" % (configfile, exc.message) msg = "Incorrect value in %s: %s" % (configfile, str(exc))
_exit_error(execname, msg, RC_BADCONFIG, log=False) _exit_error(execname, msg, RC_BADCONFIG, log=False)
except configparser.Error: except configparser.Error:
_exit_error(execname, "Incorrect configuration file: %s" % configfile, _exit_error(execname, "Incorrect configuration file: %s" % configfile,

View File

@ -105,7 +105,7 @@ class PathFilter(CommandFilter):
""" """
def match(self, userargs): def match(self, userargs):
command, arguments = userargs[0], userargs[1:] arguments = userargs[1:]
equal_args_num = len(self.args) == len(arguments) equal_args_num = len(self.args) == len(arguments)
exec_is_valid = super(PathFilter, self).match(userargs) exec_is_valid = super(PathFilter, self).match(userargs)

View File

@ -19,7 +19,6 @@
# #
from six.moves import configparser from six.moves import configparser
import logging import logging
import logging.handlers import logging.handlers
@ -40,6 +39,7 @@ class FilterMatchNotExecutable(Exception):
This exception is raised when a filter matched but no executable was This exception is raised when a filter matched but no executable was
found. found.
""" """
def __init__(self, match=None, **kwargs): def __init__(self, match=None, **kwargs):
self.match = match self.match = match

View File

@ -8,7 +8,7 @@
""" """
Command-line interface for Service Manager (SM) Command-line interface for Service Manager (SM)
""" """
from __future__ import print_function
import argparse import argparse
import httplib2 import httplib2
import logging import logging
@ -249,7 +249,7 @@ class SmcShell(object):
client = cgclient.get_client(api_version, **(args.__dict__)) client = cgclient.get_client(api_version, **(args.__dict__))
nargs = args.__dict__ # nargs = args.__dict__
# nargs['neutron_endpoint'] = client.neutron_endpoint # nargs['neutron_endpoint'] = client.neutron_endpoint
# client.neutronClient = get_neutron_client(**nargs) # client.neutronClient = get_neutron_client(**nargs)
@ -284,8 +284,9 @@ def main():
SmcShell().main(sys.argv[1:]) SmcShell().main(sys.argv[1:])
except Exception as e: except Exception as e:
print >> sys.stderr, e print(e, file=sys.stderr)
sys.exit(1) sys.exit(1)
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -6,7 +6,6 @@
# SPDX-License-Identifier: Apache-2.0 # SPDX-License-Identifier: Apache-2.0
# #
# #
from sm_client import exc
from sm_client.common import base from sm_client.common import base

View File

@ -7,9 +7,9 @@
# SPDX-License-Identifier: Apache-2.0 # SPDX-License-Identifier: Apache-2.0
# #
# #
from sm_client import exc
from sm_client.common import base from sm_client.common import base
class SmcNode(base.Resource): class SmcNode(base.Resource):
def __repr__(self): def __repr__(self):
return "<SmcNode %s>" % self._info return "<SmcNode %s>" % self._info

View File

@ -16,6 +16,7 @@ def _print_sm_service_node_show(node):
'availability_status', 'ready_state'] 'availability_status', 'ready_state']
utils.print_mapping(node, fields, wrap=72) utils.print_mapping(node, fields, wrap=72)
def do_servicenode_list(cc, args): def do_servicenode_list(cc, args):
"""List Service Nodes.""" """List Service Nodes."""
try: try:
@ -44,6 +45,6 @@ def do_servicenode_show(cc, args):
"requires 'admin' level") "requires 'admin' level")
else: else:
if node is None: if node is None:
print "Service node %s could not be found" % args.node print("Service node %s could not be found" % args.node)
return return
_print_sm_service_node_show(node) _print_sm_service_node_show(node)

View File

@ -53,7 +53,7 @@ def do_service_show(cc, args):
"requires 'admin' level") "requires 'admin' level")
else: else:
if service is None: if service is None:
print "Service %s could not be found" % args.service print("Service %s could not be found" % args.service)
return return
if service.status: if service.status:
setattr(service, 'state', service.state + '-' + service.status) setattr(service, 'state', service.state + '-' + service.status)

View File

@ -7,7 +7,6 @@
# SPDX-License-Identifier: Apache-2.0 # SPDX-License-Identifier: Apache-2.0
# #
# #
from sm_client import exc
from sm_client.common import base from sm_client.common import base

View File

@ -45,7 +45,7 @@ def do_servicegroup_show(cc, args):
"requires 'admin' level") "requires 'admin' level")
else: else:
if servicegroup is None: if servicegroup is None:
print "Service group %s could not be found" % args.servicegroup print("Service group %s could not be found" % args.servicegroup)
return return
if servicegroup.status: if servicegroup.status:
setattr(servicegroup, 'state', servicegroup.state + '-' + setattr(servicegroup, 'state', servicegroup.state + '-' +

View File

@ -20,7 +20,7 @@ def get_pid(pid_file):
pid = f.readline().strip('\n ') pid = f.readline().strip('\n ')
try: try:
pid = int(pid) pid = int(pid)
except: except Exception as e:
pid = -1 pid = -1
return pid return pid
return -1 return -1
@ -39,7 +39,7 @@ def get_process_name(pid):
name = ntpath.basename(cmd_line[1]) name = ntpath.basename(cmd_line[1])
return name return name
except: except Exception as e:
# most likely it is a leftover pid # most likely it is a leftover pid
return '' return ''
@ -122,7 +122,7 @@ def main():
if args.pid_file: if args.pid_file:
msg += "%-25s" % (pid_file) msg += "%-25s" % (pid_file)
msg += "%-10s %20s" % (row[3], row[4]) msg += "%-10s %20s" % (row[3], row[4])
print msg print(msg)
print("%s" % ('-' * len)) print("%s" % ('-' * len))
@ -193,9 +193,9 @@ def main():
try: try:
sys.stdout.close() sys.stdout.close()
except: except Exception as e:
pass pass
try: try:
sys.stderr.close() sys.stderr.close()
except: except Exception as e:
pass pass

45
tox.ini
View File

@ -51,40 +51,11 @@ commands =
[flake8] [flake8]
# The following are being suppressed for now # The following are being suppressed for now
# E114 indentation is not a multiple of four (comment)
# E116 unexpected indentation (comment)
# E121 continuation line under-indented for hanging indent
# E122 continuation line missing indentation or outdented
# E123 closing bracket does not match indentation of opening bracket's line
# E124 closing bracket does not match visual indentation
# E125 continuation line with same indent as next logical line
# E126 continuation line over-indented for hanging indent
# E127 continuation line over-indented for visual indent
# E128 continuation line under-indented for visual indent
# E129 visually indented line with same indent as next logical line
# E131 continuation line unaligned for hanging indent
# E201 whitespace after '('
# E228 missing whitespace around modulo operator
# E231 missing whitespace after ','
# E241 multiple spaces after ':'
# E251 unexpected spaces around keyword / parameter equals
# E265 block comment should start with '#'
# E271 multiple spaces after keyword
# E302 expected 2 blank lines, found 1
# E303 too many blank lines
# E305 expected 2 blank lines after class or function definition, found 1
# E402 module level import not at top of file # E402 module level import not at top of file
# E713 test for membership should be 'not in'
# E714 test for object identity should be 'is not'
# E722 do not use bare except'
# E731 do not assign a lambda expression, use a def
# E999 SyntaxError: invalid syntax (this is likely python3)
# - hacking codes - # - hacking codes -
# H102: license header not found # H102: license header not found
# H104: File contains nothing but comments # H104: File contains nothing but comments
# H105: Don't use author tags # H105: Don't use author tags
# H201: no 'except:'
# H233: Python 3.x incompatible use of print operator
# H306: imports not in alphabetical order # H306: imports not in alphabetical order
# H401: docstring should not start with a space # H401: docstring should not start with a space
# H403: multi line docstrings should end on a new line # H403: multi line docstrings should end on a new line
@ -92,23 +63,15 @@ commands =
# H405: multi line docstring summary not separated with an empty line # H405: multi line docstring summary not separated with an empty line
# H501: Do not use locals() for string formatting # H501: Do not use locals() for string formatting
# - errors - # - errors -
# F401 <foo> imported but unused
# F811 redefinition of unused '<foo>' from line <x> # F811 redefinition of unused '<foo>' from line <x>
# F821 undefined name 'e' # F821 undefined name 'e'
# F841 local variable 'foo' is assigned to but never used
# - bugbear - # - bugbear -
# B001 Do not use bare `except:`. Prefer `except Exception:`. If you're sure what you're doing, be explicit and write `except BaseException:`.
# B004 Using `hasattr(x, '__call__')` to test if `x` is callable is unreliable.
# B006 Do not use mutable data structures for argument defaults. (python3) # B006 Do not use mutable data structures for argument defaults. (python3)
# B007 Loop control variable 'key' not used within the loop body. If this is intended, start the name with an underscore.
# B008 Do not perform calls in argument defaults. The call is performed only once at function definition time. # B008 Do not perform calls in argument defaults. The call is performed only once at function definition time.
# B305 `.next()` is not a thing on Python 3. Use the `next()` builtin. For Python 2 compatibility, use `six.next()`. ignore= E402,
# B306 `BaseException.message` has been deprecated as of Python 2.6 and is removed in Python 3. H102,H104,H105,H106,H306,H401,H403,H404,H405,H501,
ignore= E114,E116,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E201,E228,E231,E241,E251,E265,E271, F811,F821,
E302,E303,E305,E402,E713,E714,E722,E731,E999, B006,B008
H102,H104,H105,H106,H201,H233,H306,H401,H403,H404,H405,H501,
F401,F811,F821,F841,
B001,B004,B006,B007,B008,B305,B306
# Enable checks which are off by default # Enable checks which are off by default
# H106 Dont put vim configuration in source files (off by default). SHOULD BE ENABLED. # H106 Dont put vim configuration in source files (off by default). SHOULD BE ENABLED.
# H203 Use assertIs(Not)None to check for None (off by default). # H203 Use assertIs(Not)None to check for None (off by default).