pylint fixes

This commit is contained in:
Lex Berezhny 2018-07-21 19:08:28 -04:00 committed by Jack Robison
parent 1f75b6a49e
commit 693a3346d2
No known key found for this signature in database
GPG key ID: DF25C68FE0239BB2
15 changed files with 44 additions and 49 deletions

View file

@ -123,7 +123,8 @@ disable=
inconsistent-return-statements, inconsistent-return-statements,
keyword-arg-before-vararg, keyword-arg-before-vararg,
assignment-from-no-return, assignment-from-no-return,
useless-return useless-return,
assignment-from-none
[REPORTS] [REPORTS]

View file

@ -15,7 +15,7 @@ class HashBlobReader:
def __del__(self): def __del__(self):
if self.finished_cb_d is None: if self.finished_cb_d is None:
log.warn("Garbage collection was called, but reader for %s was not closed yet", log.warning("Garbage collection was called, but reader for %s was not closed yet",
self.read_handle.name) self.read_handle.name)
self.close() self.close()
@ -28,5 +28,3 @@ class HashBlobReader:
return return
self.read_handle.close() self.read_handle.close()
self.finished_cb_d = self.finished_cb(self) self.finished_cb_d = self.finished_cb(self)

View file

@ -18,7 +18,7 @@ class HashBlobWriter:
def __del__(self): def __del__(self):
if self.finished_cb_d is None: if self.finished_cb_d is None:
log.warn("Garbage collection was called, but writer was not closed yet") log.warning("Garbage collection was called, but writer was not closed yet")
self.close() self.close()
@property @property

View file

@ -16,4 +16,3 @@ class BlobInfo:
self.blob_hash = blob_hash self.blob_hash = blob_hash
self.blob_num = blob_num self.blob_num = blob_num
self.length = length self.length = length

View file

@ -224,5 +224,3 @@ class ConnectionManager:
del self._connections_closing[peer] del self._connections_closing[peer]
d.callback(True) d.callback(True)
return connection_was_made return connection_was_made

View file

@ -147,7 +147,7 @@ def get_sd_hash(stream_info):
get('source', {}).\ get('source', {}).\
get('source') get('source')
if not result: if not result:
log.warn("Unable to get sd_hash") log.warning("Unable to get sd_hash")
return result return result

View file

@ -919,7 +919,7 @@ class Daemon(AuthJSONRPCServer):
if isinstance(new_settings[key], setting_type): if isinstance(new_settings[key], setting_type):
conf.settings.update({key: new_settings[key]}, conf.settings.update({key: new_settings[key]},
data_types=(conf.TYPE_RUNTIME, conf.TYPE_PERSISTED)) data_types=(conf.TYPE_RUNTIME, conf.TYPE_PERSISTED))
elif setting_type is dict and isinstance(new_settings[key], (unicode, str)): elif setting_type is dict and isinstance(new_settings[key], str):
decoded = json.loads(str(new_settings[key])) decoded = json.loads(str(new_settings[key]))
conf.settings.update({key: decoded}, conf.settings.update({key: decoded},
data_types=(conf.TYPE_RUNTIME, conf.TYPE_PERSISTED)) data_types=(conf.TYPE_RUNTIME, conf.TYPE_PERSISTED))
@ -2917,10 +2917,7 @@ class Daemon(AuthJSONRPCServer):
if datastore_len: if datastore_len:
for k, v in data_store.items(): for k, v in data_store.items():
for contact, value, lastPublished, originallyPublished, originalPublisherID in v: for contact, value, lastPublished, originallyPublished, originalPublisherID in v:
if contact in hosts: blobs = blobs.get(contact, [])
blobs = hosts[contact]
else:
blobs = []
blobs.append(k.encode('hex')) blobs.append(k.encode('hex'))
hosts[contact] = blobs hosts[contact] = blobs

View file

@ -1,3 +1,4 @@
# pylint: skip-file
import json import json
import os import os
import sys import sys
@ -63,7 +64,7 @@ def main():
return return
elif method in ['version', '--version']: elif method in ['version', '--version']:
print utils.json_dumps_pretty(get_platform(get_ip=False)) print(utils.json_dumps_pretty(get_platform(get_ip=False)))
return return
if method not in Daemon.callable_methods: if method not in Daemon.callable_methods:
@ -106,16 +107,16 @@ def main():
result = api.call(method, kwargs) result = api.call(method, kwargs)
if isinstance(result, basestring): if isinstance(result, basestring):
# printing the undumped string is prettier # printing the undumped string is prettier
print result print(result)
else: else:
print utils.json_dumps_pretty(result) print(utils.json_dumps_pretty(result))
except (RPCError, KeyError, JSONRPCException, HTTPError) as err: except (RPCError, KeyError, JSONRPCException, HTTPError) as err:
if isinstance(err, HTTPError): if isinstance(err, HTTPError):
error_body = err.read() error_body = err.read()
try: try:
error_data = json.loads(error_body) error_data = json.loads(error_body)
except ValueError: except ValueError:
print ( print(
"There was an error, and the response was not valid JSON.\n" + "There was an error, and the response was not valid JSON.\n" +
"Raw JSONRPC response:\n" + error_body "Raw JSONRPC response:\n" + error_body
) )
@ -124,8 +125,8 @@ def main():
print_error(error_data['error']['message'] + "\n", suggest_help=False) print_error(error_data['error']['message'] + "\n", suggest_help=False)
if 'data' in error_data['error'] and 'traceback' in error_data['error']['data']: if 'data' in error_data['error'] and 'traceback' in error_data['error']['data']:
print "Here's the traceback for the error you encountered:" print("Here's the traceback for the error you encountered:")
print "\n".join(error_data['error']['data']['traceback']) print("\n".join(error_data['error']['data']['traceback']))
print_help_for_command(method) print_help_for_command(method)
elif isinstance(err, RPCError): elif isinstance(err, RPCError):
@ -133,7 +134,7 @@ def main():
# print_help_for_command(method) # print_help_for_command(method)
else: else:
print_error("Something went wrong\n", suggest_help=False) print_error("Something went wrong\n", suggest_help=False)
print str(err) print(str(err))
return 1 return 1
@ -160,18 +161,18 @@ def guess_type(x, key=None):
def print_help_suggestion(): def print_help_suggestion():
print "See `{} help` for more information.".format(os.path.basename(sys.argv[0])) print("See `{} help` for more information.".format(os.path.basename(sys.argv[0])))
def print_error(message, suggest_help=True): def print_error(message, suggest_help=True):
error_style = colorama.Style.BRIGHT + colorama.Fore.RED error_style = colorama.Style.BRIGHT + colorama.Fore.RED
print error_style + "ERROR: " + message + colorama.Style.RESET_ALL print(error_style + "ERROR: " + message + colorama.Style.RESET_ALL)
if suggest_help: if suggest_help:
print_help_suggestion() print_help_suggestion()
def print_help(): def print_help():
print "\n".join([ print("\n".join([
"NAME", "NAME",
" lbrynet-cli - LBRY command line client.", " lbrynet-cli - LBRY command line client.",
"", "",
@ -184,13 +185,13 @@ def print_help():
" lbrynet-cli --conf ~/l1.conf status # like above but using ~/l1.conf as config file", " lbrynet-cli --conf ~/l1.conf status # like above but using ~/l1.conf as config file",
" lbrynet-cli resolve_name what # resolve a name", " lbrynet-cli resolve_name what # resolve a name",
" lbrynet-cli help resolve_name # get help for a command", " lbrynet-cli help resolve_name # get help for a command",
]) ]))
def print_help_for_command(command): def print_help_for_command(command):
fn = Daemon.callable_methods.get(command) fn = Daemon.callable_methods.get(command)
if fn: if fn:
print "Help for %s method:\n%s" % (command, fn.__doc__) print("Help for %s method:\n%s" % (command, fn.__doc__))
def wrap_list_to_term_width(l, width=None, separator=', ', prefix=''): def wrap_list_to_term_width(l, width=None, separator=', ', prefix=''):

View file

@ -133,14 +133,14 @@ def run_terminal(callable_methods, started_daemon, quiet=False):
def help(method_name=None): def help(method_name=None):
if not method_name: if not method_name:
print "Available api functions: " print("Available api functions: ")
for name in callable_methods: for name in callable_methods:
print "\t%s" % name print("\t%s" % name)
return return
if method_name not in callable_methods: if method_name not in callable_methods:
print "\"%s\" is not a recognized api function" print("\"%s\" is not a recognized api function")
return return
print callable_methods[method_name].__doc__ print(callable_methods[method_name].__doc__)
return return
locs.update({'help': help}) locs.update({'help': help})
@ -148,7 +148,7 @@ def run_terminal(callable_methods, started_daemon, quiet=False):
if started_daemon: if started_daemon:
def exit(status=None): def exit(status=None):
if not quiet: if not quiet:
print "Stopping lbrynet-daemon..." print("Stopping lbrynet-daemon...")
callable_methods['daemon_stop']() callable_methods['daemon_stop']()
return sys.exit(status) return sys.exit(status)
@ -158,7 +158,7 @@ def run_terminal(callable_methods, started_daemon, quiet=False):
try: try:
reactor.callLater(0, reactor.stop) reactor.callLater(0, reactor.stop)
except Exception as err: except Exception as err:
print "error stopping reactor: ", err print("error stopping reactor: {}".format(err))
return sys.exit(status) return sys.exit(status)
locs.update({'exit': exit}) locs.update({'exit': exit})
@ -186,19 +186,19 @@ def threaded_terminal(started_daemon, quiet):
def start_lbrynet_console(quiet, use_existing_daemon, useauth): def start_lbrynet_console(quiet, use_existing_daemon, useauth):
if not utils.check_connection(): if not utils.check_connection():
print "Not connected to internet, unable to start" print("Not connected to internet, unable to start")
raise Exception("Not connected to internet, unable to start") raise Exception("Not connected to internet, unable to start")
if not quiet: if not quiet:
print "Starting lbrynet-console..." print("Starting lbrynet-console...")
try: try:
get_client().status() get_client().status()
d = defer.succeed(False) d = defer.succeed(False)
if not quiet: if not quiet:
print "lbrynet-daemon is already running, connecting to it..." print("lbrynet-daemon is already running, connecting to it...")
except: except:
if not use_existing_daemon: if not use_existing_daemon:
if not quiet: if not quiet:
print "Starting lbrynet-daemon..." print("Starting lbrynet-daemon...")
analytics_manager = analytics.Manager.new_instance() analytics_manager = analytics.Manager.new_instance()
d = start_server_and_listen(useauth, analytics_manager, quiet) d = start_server_and_listen(useauth, analytics_manager, quiet)
else: else:

View file

@ -1,3 +1,4 @@
# pylint: skip-file
import os import os
import json import json
import urlparse import urlparse

View file

@ -1,3 +1,4 @@
# pylint: skip-file
import logging import logging
from six.moves.urllib import parse as urlparse from six.moves.urllib import parse as urlparse
import json import json
@ -57,7 +58,7 @@ class JSONRPCError:
} }
def __init__(self, message, code=CODE_APPLICATION_ERROR, traceback=None, data=None): def __init__(self, message, code=CODE_APPLICATION_ERROR, traceback=None, data=None):
assert isinstance(code, (int, long)), "'code' must be an int" assert isinstance(code, int), "'code' must be an int"
assert (data is None or isinstance(data, dict)), "'data' must be None or a dict" assert (data is None or isinstance(data, dict)), "'data' must be None or a dict"
self.code = code self.code = code
if message is None: if message is None:
@ -401,7 +402,7 @@ class AuthJSONRPCServer(AuthorizedBase):
) )
return server.NOT_DONE_YET return server.NOT_DONE_YET
if args == EMPTY_PARAMS or args == []: if args in (EMPTY_PARAMS, []):
_args, _kwargs = (), {} _args, _kwargs = (), {}
elif isinstance(args, dict): elif isinstance(args, dict):
_args, _kwargs = (), args _args, _kwargs = (), args

View file

@ -39,7 +39,7 @@ def migrate_blobs_db(db_dir):
blobs_db_cursor.execute( blobs_db_cursor.execute(
"ALTER TABLE blobs ADD COLUMN should_announce integer NOT NULL DEFAULT 0") "ALTER TABLE blobs ADD COLUMN should_announce integer NOT NULL DEFAULT 0")
else: else:
log.warn("should_announce already exists somehow, proceeding anyways") log.warning("should_announce already exists somehow, proceeding anyways")
# if lbryfile_info.db doesn't exist, skip marking blobs as should_announce = True # if lbryfile_info.db doesn't exist, skip marking blobs as should_announce = True
if not os.path.isfile(lbryfile_info_db): if not os.path.isfile(lbryfile_info_db):
@ -83,4 +83,3 @@ def migrate_blobs_db(db_dir):
blobs_db_file.commit() blobs_db_file.commit()
blobs_db_file.close() blobs_db_file.close()
lbryfile_info_file.close() lbryfile_info_file.close()

View file

@ -127,8 +127,13 @@ class KademliaProtocol(protocol.DatagramProtocol):
if contact.protocolVersion == 0: if contact.protocolVersion == 0:
if method == b'store': if method == b'store':
blob_hash, token, port, originalPublisherID, age = args blob_hash, token, port, originalPublisherID, age = args
args = (blob_hash, {b'token': token, b'port': port, b'lbryid': originalPublisherID}, originalPublisherID, args = (
False) blob_hash, {
b'token': token,
b'port': port,
b'lbryid': originalPublisherID
}, originalPublisherID, False
)
return args return args
return args return args
if args and isinstance(args[-1], dict): if args and isinstance(args[-1], dict):

View file

@ -178,12 +178,7 @@ class TreeRoutingTable:
by this node by this node
""" """
bucketIndex = self._kbucketIndex(contactID) bucketIndex = self._kbucketIndex(contactID)
try: return self._buckets[bucketIndex].getContact(contactID)
contact = self._buckets[bucketIndex].getContact(contactID)
except ValueError:
raise
else:
return contact
def getRefreshList(self, startIndex=0, force=False): def getRefreshList(self, startIndex=0, force=False):
""" Finds all k-buckets that need refreshing, starting at the """ Finds all k-buckets that need refreshing, starting at the

View file

@ -288,7 +288,7 @@ def format_amount_value(obj):
COIN = 100000000 COIN = 100000000
if isinstance(obj, dict): if isinstance(obj, dict):
for k, v in obj.items(): for k, v in obj.items():
if k == 'amount' or k == 'effective_amount': if k in ('amount', 'effective_amount'):
if not isinstance(obj[k], float): if not isinstance(obj[k], float):
obj[k] = float(obj[k]) / float(COIN) obj[k] = float(obj[k]) / float(COIN)
elif k == 'supports' and isinstance(v, list): elif k == 'supports' and isinstance(v, list):