Pylint cleanup.

Add more dynamic attribute info to IPATypeChecker in make-lint. Remove
unnecessary pylint comments. Fix false positivies introduced by Pylint 0.26.

https://fedorahosted.org/freeipa/ticket/3379
This commit is contained in:
Jan Cholasta 2013-01-28 14:55:20 +01:00 committed by Martin Kosek
parent 41d11f443b
commit 77bb4b5177
10 changed files with 78 additions and 76 deletions

View File

@ -1350,7 +1350,6 @@ def get_ca_cert_from_file(url):
Raises errors.FileError if unable to write cert. Raises errors.FileError if unable to write cert.
''' '''
# pylint: disable=E1101
try: try:
parsed = urlparse.urlparse(url, 'file') parsed = urlparse.urlparse(url, 'file')
except Exception, e: except Exception, e:

View File

@ -478,10 +478,10 @@ class Command(HasParam):
>>> list(c._repr_iter(login=u'Okay.', passwd=u'Private!')) >>> list(c._repr_iter(login=u'Okay.', passwd=u'Private!'))
["u'Okay.'", "passwd=u'********'"] ["u'Okay.'", "passwd=u'********'"]
""" """
for arg in self.args(): #pylint: disable=E1102 for arg in self.args():
value = params.get(arg.name, None) value = params.get(arg.name, None)
yield repr(arg.safe_value(value)) yield repr(arg.safe_value(value))
for option in self.options(): #pylint: disable=E1102 for option in self.options():
if option.name not in params: if option.name not in params:
continue continue
value = params[option.name] value = params[option.name]
@ -506,7 +506,7 @@ class Command(HasParam):
def __args_2_params(self, values): def __args_2_params(self, values):
multivalue = False multivalue = False
for (i, arg) in enumerate(self.args()): #pylint: disable=E1102 for (i, arg) in enumerate(self.args()):
assert not multivalue assert not multivalue
if len(values) > i: if len(values) > i:
if arg.multivalue: if arg.multivalue:
@ -784,7 +784,7 @@ class Command(HasParam):
else: else:
self.max_args = None self.max_args = None
self._create_param_namespace('options') self._create_param_namespace('options')
params_nosort = tuple(self.args()) + tuple(self.options()) #pylint: disable=E1102 params_nosort = tuple(self.args()) + tuple(self.options())
def get_key(p): def get_key(p):
if p.required: if p.required:
if p.sortorder < 0: if p.sortorder < 0:
@ -963,7 +963,7 @@ class Command(HasParam):
rv = 0 rv = 0
order = [p.name for p in self.output_params()] #pylint: disable=E1102 order = [p.name for p in self.output_params()]
if options.get('all', False): if options.get('all', False):
order.insert(0, 'dn') order.insert(0, 'dn')
print_all = True print_all = True
@ -973,8 +973,8 @@ class Command(HasParam):
if options.get('raw', False): if options.get('raw', False):
labels = None labels = None
else: else:
labels = dict((p.name, unicode(p.label)) for p in self.output_params()) #pylint: disable=E1102 labels = dict((p.name, unicode(p.label)) for p in self.output_params())
flags = dict((p.name, p.flags) for p in self.output_params()) #pylint: disable=E1102 flags = dict((p.name, p.flags) for p in self.output_params())
for o in self.output: for o in self.output:
outp = self.output[o] outp = self.output[o]
@ -1112,7 +1112,7 @@ class Object(HasParam):
self.__get_attrs('Property'), sort=False, name_attr='attr_name' self.__get_attrs('Property'), sort=False, name_attr='attr_name'
) )
self._create_param_namespace('params') self._create_param_namespace('params')
pkeys = filter(lambda p: p.primary_key, self.params()) #pylint: disable=E1102 pkeys = filter(lambda p: p.primary_key, self.params())
if len(pkeys) > 1: if len(pkeys) > 1:
raise ValueError( raise ValueError(
'%s (Object) has multiple primary keys: %s' % ( '%s (Object) has multiple primary keys: %s' % (
@ -1123,7 +1123,7 @@ class Object(HasParam):
if len(pkeys) == 1: if len(pkeys) == 1:
self.primary_key = pkeys[0] self.primary_key = pkeys[0]
self.params_minus_pk = NameSpace( self.params_minus_pk = NameSpace(
filter(lambda p: not p.primary_key, self.params()), sort=False #pylint: disable=E1102 filter(lambda p: not p.primary_key, self.params()), sort=False
) )
else: else:
self.primary_key = None self.primary_key = None
@ -1141,7 +1141,7 @@ class Object(HasParam):
if len(names) == 1 and not isinstance(names[0], (Param, str)): if len(names) == 1 and not isinstance(names[0], (Param, str)):
names = names[0] names = names[0]
minus = frozenset(names) minus = frozenset(names)
for param in self.params(): #pylint: disable=E1102 for param in self.params():
if param.name in minus or param in minus: if param.name in minus or param in minus:
continue continue
yield param yield param

View File

@ -231,7 +231,7 @@ class KRB5_CCache(object):
error_code = e.args[0] error_code = e.args[0]
if error_code == KRB5_CC_NOTFOUND: if error_code == KRB5_CC_NOTFOUND:
raise KeyError('"%s" credential not found in "%s" ccache' % \ raise KeyError('"%s" credential not found in "%s" ccache' % \
(krbV_principal.name, self.ccache_str())) #pylint: disable=E1103 (krbV_principal.name, self.ccache_str()))
raise e raise e
except Exception, e: except Exception, e:
raise e raise e
@ -282,7 +282,7 @@ class KRB5_CCache(object):
authtime, starttime, endtime, renew_till = cred[3] authtime, starttime, endtime, renew_till = cred[3]
self.debug('get_credential_times: principal=%s, authtime=%s, starttime=%s, endtime=%s, renew_till=%s', self.debug('get_credential_times: principal=%s, authtime=%s, starttime=%s, endtime=%s, renew_till=%s',
krbV_principal.name, #pylint: disable=E1103 krbV_principal.name,
krb5_format_time(authtime), krb5_format_time(starttime), krb5_format_time(authtime), krb5_format_time(starttime),
krb5_format_time(endtime), krb5_format_time(renew_till)) krb5_format_time(endtime), krb5_format_time(renew_till))
@ -291,7 +291,7 @@ class KRB5_CCache(object):
except KeyError, e: except KeyError, e:
raise e raise e
except Exception, e: except Exception, e:
self.error('get_credential_times failed, principal="%s" error="%s"', krbV_principal.name, e) #pylint: disable=E1103 self.error('get_credential_times failed, principal="%s" error="%s"', krbV_principal.name, e)
raise e raise e
def credential_is_valid(self, principal): def credential_is_valid(self, principal):

View File

@ -1101,8 +1101,7 @@ class Int(Number):
) )
def __init__(self, name, *rules, **kw): def __init__(self, name, *rules, **kw):
#pylint: disable=E1003 super(Int, self).__init__(name, *rules, **kw)
super(Number, self).__init__(name, *rules, **kw)
if (self.minvalue > self.maxvalue) and (self.minvalue is not None and self.maxvalue is not None): if (self.minvalue > self.maxvalue) and (self.minvalue is not None and self.maxvalue is not None):
raise ValueError( raise ValueError(
@ -1257,7 +1256,6 @@ class Decimal(Number):
) )
def _enforce_numberclass(self, value): def _enforce_numberclass(self, value):
#pylint: disable=E1101
numberclass = value.number_class() numberclass = value.number_class()
if numberclass not in self.numberclass: if numberclass not in self.numberclass:
raise ValidationError(name=self.get_param_name(), raise ValidationError(name=self.get_param_name(),
@ -1281,7 +1279,7 @@ class Decimal(Number):
def _remove_exponent(self, value): def _remove_exponent(self, value):
assert type(value) is decimal.Decimal assert type(value) is decimal.Decimal
if not self.exponential: #pylint: disable=E1101 if not self.exponential:
try: try:
# adopted from http://docs.python.org/library/decimal.html # adopted from http://docs.python.org/library/decimal.html
value = value.quantize(decimal.Decimal(1)) \ value = value.quantize(decimal.Decimal(1)) \
@ -1499,7 +1497,7 @@ class Str(Data):
Do not allow leading/trailing spaces. Do not allow leading/trailing spaces.
""" """
assert type(value) is unicode assert type(value) is unicode
if self.noextrawhitespace is False: #pylint: disable=E1101 if self.noextrawhitespace is False:
return return
if len(value) != len(value.strip()): if len(value) != len(value.strip()):
return _('Leading and trailing spaces are not allowed') return _('Leading and trailing spaces are not allowed')

View File

@ -630,7 +630,7 @@ class DNSRecord(Str):
return super(DNSRecord, self)._convert_scalar(value, index) return super(DNSRecord, self)._convert_scalar(value, index)
def normalize(self, value): def normalize(self, value):
if self.normalizedns: #pylint: disable=E1101 if self.normalizedns:
if isinstance(value, (tuple, list)): if isinstance(value, (tuple, list)):
value = tuple( value = tuple(
self._normalize_parts(v) for v in value \ self._normalize_parts(v) for v in value \
@ -667,7 +667,7 @@ class DNSRecord(Str):
return value return value
def _rule_validatedns(self, _, value): def _rule_validatedns(self, _, value):
if not self.validatedns: #pylint: disable=E1101 if not self.validatedns:
return return
if value is None: if value is None:

View File

@ -64,12 +64,6 @@ escaping and unescapin.
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
# FIXME: The use of properties for the attributes timestamp, expires
# and max_age produce a pylint error which is a false positive, this
# is a known bug in pylint (http://www.logilab.org/ticket/89092,
# http://www.logilab.org/ticket/89786) after the pylint bug is fixed
# the disables for E0202 should be removed.
class Cookie(object): class Cookie(object):
''' '''
A Cookie object has the following attributes: A Cookie object has the following attributes:
@ -366,7 +360,7 @@ class Cookie(object):
self.timestamp = timestamp self.timestamp = timestamp
@property @property
def timestamp(self): #pylint: disable=E0202 def timestamp(self):
''' '''
The UTC moment at which cookie was received for purposes of The UTC moment at which cookie was received for purposes of
computing the expiration given a Max-Age offset. The computing the expiration given a Max-Age offset. The
@ -389,7 +383,7 @@ class Cookie(object):
return self._timestamp return self._timestamp
@timestamp.setter @timestamp.setter
def timestamp(self, value): #pylint: disable=E0202 def timestamp(self, value):
if value is None: if value is None:
self._timestamp = None self._timestamp = None
elif isinstance(value, datetime.datetime): elif isinstance(value, datetime.datetime):
@ -403,7 +397,7 @@ class Cookie(object):
value.__class__.__name__) value.__class__.__name__)
@property @property
def expires(self): #pylint: disable=E0202 def expires(self):
''' '''
The expiration timestamp (in UTC) as a datetime object for the The expiration timestamp (in UTC) as a datetime object for the
cookie, or None if not set. cookie, or None if not set.
@ -415,7 +409,7 @@ class Cookie(object):
return self._expires return self._expires
@expires.setter @expires.setter
def expires(self, value): #pylint: disable=E0202 def expires(self, value):
if value is None: if value is None:
self._expires = None self._expires = None
elif isinstance(value, datetime.datetime): elif isinstance(value, datetime.datetime):
@ -429,7 +423,7 @@ class Cookie(object):
value.__class__.__name__) value.__class__.__name__)
@property @property
def max_age(self): #pylint: disable=E0202 def max_age(self):
''' '''
The lifetime duration of the cookie. Computed as an offset The lifetime duration of the cookie. Computed as an offset
from the cookie's timestamp. from the cookie's timestamp.
@ -437,7 +431,7 @@ class Cookie(object):
return self._max_age return self._max_age
@max_age.setter @max_age.setter
def max_age(self, value): #pylint: disable=E0202 def max_age(self, value):
if value is None: if value is None:
self._max_age = None self._max_age = None
else: else:

View File

@ -775,7 +775,7 @@ def bind_port_responder(port, socket_type=socket.SOCK_STREAM, socket_timeout=Non
connection, client_address = s.accept() connection, client_address = s.accept()
try: try:
if responder_data: if responder_data:
connection.sendall(responder_data) #pylint: disable=E1101 connection.sendall(responder_data)
finally: finally:
connection.close() connection.close()
elif socket_type == socket.SOCK_DGRAM: elif socket_type == socket.SOCK_DGRAM:

View File

@ -200,14 +200,15 @@ class NSSConnection(httplib.HTTPConnection, NSSAddressFamilyFallback):
def _create_socket(self): def _create_socket(self):
# TODO: remove the try block once python-nss is guaranteed to contain # TODO: remove the try block once python-nss is guaranteed to contain
# these values # these values
try : try:
ssl_enable_renegotiation = SSL_ENABLE_RENEGOTIATION #pylint: disable=E0602 #pylint: disable=E1101
ssl_require_safe_negotiation = SSL_REQUIRE_SAFE_NEGOTIATION #pylint: disable=E0602 ssl_enable_renegotiation = ssl.SSL_ENABLE_RENEGOTIATION
ssl_renegotiate_requires_xtn = SSL_RENEGOTIATE_REQUIRES_XTN #pylint: disable=E0602 ssl_require_safe_negotiation = ssl.SSL_REQUIRE_SAFE_NEGOTIATION
except : ssl_renegotiate_requires_xtn = ssl.SSL_RENEGOTIATE_REQUIRES_XTN
ssl_enable_renegotiation = 20 except:
ssl_require_safe_negotiation = 21 ssl_enable_renegotiation = 20
ssl_renegotiate_requires_xtn = 2 ssl_require_safe_negotiation = 21
ssl_renegotiate_requires_xtn = 2
# Create the socket here so we can do things like let the caller # Create the socket here so we can do things like let the caller
# override the NSS callbacks # override the NSS callbacks

View File

@ -109,7 +109,7 @@ class updateclient(backend.Executioner):
def order(self, updatetype): def order(self, updatetype):
"""Return plugins of the given updatetype in sorted order. """Return plugins of the given updatetype in sorted order.
""" """
ordered = [plugin for plugin in api.Updater() # pylint: disable=E1101 ordered = [plugin for plugin in api.Updater()
if plugin.updatetype == updatetype] if plugin.updatetype == updatetype]
ordered.sort(key=lambda p: p.order) ordered.sort(key=lambda p: p.order)
return ordered return ordered
@ -143,7 +143,7 @@ class updateclient(backend.Executioner):
""" """
Execute the update plugin. Execute the update plugin.
""" """
return self.Updater[method](**kw) #pylint: disable=E1101 return self.Updater[method](**kw)
def restart(self, dm_password, live_run): def restart(self, dm_password, live_run):
dsrestart = DSRestart() dsrestart = DSRestart()

View File

@ -37,49 +37,59 @@ except ImportError:
# File names to ignore when searching for python source files # File names to ignore when searching for python source files
IGNORE_FILES = ('.*', '*~', '*.in', '*.pyc', '*.pyo') IGNORE_FILES = ('.*', '*~', '*.in', '*.pyc', '*.pyo')
IGNORE_PATHS = ('build', 'rpmbuild', 'dist', 'install/po/test_i18n.py', 'lite-server.py', IGNORE_PATHS = ('build', 'rpmbuild', 'dist', 'install/po/test_i18n.py',
'make-lint', 'make-test', 'tests') 'lite-server.py', 'make-lint', 'make-test', 'tests')
class IPATypeChecker(TypeChecker): class IPATypeChecker(TypeChecker):
# 'class': ('generated', 'properties',) NAMESPACE_ATTRS = ['Command', 'Object', 'Method', 'Property', 'Backend',
'Updater']
LOGGING_ATTRS = ['log', 'debug', 'info', 'warning', 'error', 'exception',
'critical']
# 'class': ['generated', 'properties']
ignore = { ignore = {
'ipalib.base.NameSpace': ['find'], # Python standard library & 3rd party classes
'krbV.Principal': ['name'],
'socket._socketobject': ['sendall'],
# should be 'subprocess.Popen'
'.Popen': ['stdin', 'stdout', 'stderr', 'pid', 'returncode', 'poll',
'wait', 'communicate'],
'urlparse.ResultMixin': ['scheme', 'netloc', 'path', 'query',
'fragment', 'username', 'password', 'hostname', 'port'],
'urlparse.ParseResult': ['params'],
# IPA classes
'ipapython.admintool.AdminTool': LOGGING_ATTRS,
'ipalib.base.NameSpace': ['add', 'mod', 'del', 'show', 'find'],
'ipalib.cli.Collector': ['__options'], 'ipalib.cli.Collector': ['__options'],
'ipalib.config.Env': ['*'], 'ipalib.config.Env': ['*'],
'ipalib.plugable.API': ['Command', 'Object', 'Method', 'Property', 'ipalib.krb_utils.KRB5_CCache': LOGGING_ATTRS,
'Backend', 'log', 'plugins'],
'ipalib.plugable.Plugin': ['Command', 'Object', 'Method', 'Property',
'Backend', 'env', 'debug', 'info', 'warning', 'error', 'critical',
'exception', 'context', 'log'],
'ipalib.plugins.misc.env': ['env'],
'ipalib.parameters.Param': ['cli_name', 'cli_short_name', 'label', 'ipalib.parameters.Param': ['cli_name', 'cli_short_name', 'label',
'doc', 'required', 'multivalue', 'primary_key', 'normalizer', 'default', 'doc', 'required', 'multivalue', 'primary_key',
'default', 'default_from', 'autofill', 'query', 'attribute', 'normalizer', 'default_from', 'autofill', 'query', 'attribute',
'include', 'exclude', 'flags', 'hint', 'alwaysask', 'sortorder', 'include', 'exclude', 'flags', 'hint', 'alwaysask', 'sortorder',
'csv', 'csv_separator', 'csv_skipspace'], 'csv', 'csv_separator', 'csv_skipspace', 'option_group'],
'ipalib.parameters.Bool': ['truths', 'falsehoods'], 'ipalib.parameters.Bool': ['truths', 'falsehoods'],
'ipalib.parameters.Int': ['minvalue', 'maxvalue'],
'ipalib.parameters.Decimal': ['minvalue', 'maxvalue', 'precision'],
'ipalib.parameters.Data': ['minlength', 'maxlength', 'length', 'ipalib.parameters.Data': ['minlength', 'maxlength', 'length',
'pattern', 'pattern_errmsg'], 'pattern', 'pattern_errmsg'],
'ipalib.parameters.Enum': ['values'], 'ipalib.parameters.Str': ['noextrawhitespace'],
'ipalib.parameters.Password': ['confirm'],
'ipalib.parameters.File': ['stdin_if_missing'], 'ipalib.parameters.File': ['stdin_if_missing'],
'urlparse.SplitResult': ['scheme', 'netloc', 'path', 'query', 'fragment', 'username', 'password', 'hostname', 'port'], 'ipalib.plugins.dns.DNSRecord': ['validatedns', 'normalizedns'],
'urlparse.ParseResult': ['scheme', 'netloc', 'path', 'params', 'query', 'fragment', 'username', 'password', 'hostname', 'port'], 'ipalib.parameters.Enum': ['values'],
'ipaserver.install.ldapupdate.LDAPUpdate' : ['log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'], 'ipalib.parameters.Number': ['minvalue', 'maxvalue'],
'ipaserver.plugins.ldap2.SchemaCache' : ['log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'], 'ipalib.parameters.Decimal': ['precision', 'exponential',
'ipaserver.plugins.ldap2.IPASimpleLDAPObject' : ['log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'], 'numberclass'],
'ipaserver.plugins.ldap2.ldap2' : ['log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'], 'ipalib.plugable.API': NAMESPACE_ATTRS + LOGGING_ATTRS,
'ipaserver.rpcserver.KerberosSession' : ['api', 'log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'], 'ipalib.plugable.Plugin': ['api', 'env'] + NAMESPACE_ATTRS +
'ipaserver.rpcserver.HTTP_Status' : ['log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'], LOGGING_ATTRS,
'ipalib.krb_utils.KRB5_CCache' : ['log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'], 'ipalib.session.AuthManager': LOGGING_ATTRS,
'ipalib.session.AuthManager' : ['log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'], 'ipalib.session.SessionAuthManager': LOGGING_ATTRS,
'ipalib.session.SessionAuthManager' : ['log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'], 'ipalib.session.SessionManager': LOGGING_ATTRS,
'ipalib.session.SessionManager' : ['log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'], 'ipaserver.install.ldapupdate.LDAPUpdate': LOGGING_ATTRS,
'ipalib.session.SessionCCache' : ['log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'], 'ipaserver.plugins.ldap2.IPASimpleLDAPObject': LOGGING_ATTRS,
'ipalib.session.MemcacheSessionManager' : ['log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'], 'ipaserver.plugins.ldap2.SchemaCache': LOGGING_ATTRS,
'ipapython.admintool.AdminTool' : ['log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'], 'ipaserver.rpcserver.KerberosSession': ['api'] + LOGGING_ATTRS,
'ipapython.cookie.Cookie' : ['log', 'debug', 'info', 'warning', 'error', 'critical', 'exception'],
} }
def _related_classes(self, klass): def _related_classes(self, klass):