core: Apply some suggestions of pyflakes.

This commit is contained in:
Valentin Lorentz 2015-08-31 15:38:35 +02:00
parent 6d60616597
commit 912d2e1538
27 changed files with 41 additions and 67 deletions

View File

@ -34,7 +34,6 @@ This module contains the basic callbacks for handling PRIVMSGs.
""" """
import re import re
import sys
import copy import copy
import time import time
from . import shlex from . import shlex
@ -46,7 +45,7 @@ from . import (conf, ircdb, irclib, ircmsgs, ircutils, log, registry,
utils, world) utils, world)
from .utils import minisix from .utils import minisix
from .utils.iter import any, all from .utils.iter import any, all
from .i18n import PluginInternationalization, internationalizeDocstring from .i18n import PluginInternationalization
_ = PluginInternationalization() _ = PluginInternationalization()
def _addressed(nick, msg, prefixChars=None, nicks=None, def _addressed(nick, msg, prefixChars=None, nicks=None,
@ -318,7 +317,6 @@ class Tokenizer(object):
ret.append(self._insideBrackets(lexer)) ret.append(self._insideBrackets(lexer))
else: else:
ret.append(self._handleToken(token)) ret.append(self._handleToken(token))
firstToken = False
return ret return ret
def tokenize(self, s): def tokenize(self, s):
@ -372,7 +370,6 @@ def tokenize(s, channel=None):
if conf.get(nested.pipeSyntax, channel): # No nesting, no pipe. if conf.get(nested.pipeSyntax, channel): # No nesting, no pipe.
pipe = True pipe = True
quotes = conf.get(conf.supybot.commands.quotes, channel) quotes = conf.get(conf.supybot.commands.quotes, channel)
start = time.time()
try: try:
ret = Tokenizer(brackets=brackets,pipe=pipe,quotes=quotes).tokenize(s) ret = Tokenizer(brackets=brackets,pipe=pipe,quotes=quotes).tokenize(s)
return ret return ret

View File

@ -266,7 +266,7 @@ def getInt(irc, msg, args, state, type=_('integer'), p=None):
def getNonInt(irc, msg, args, state, type=_('non-integer value')): def getNonInt(irc, msg, args, state, type=_('non-integer value')):
try: try:
i = _int(args[0]) _int(args[0])
state.errorInvalid(type, args[0]) state.errorInvalid(type, args[0])
except ValueError: except ValueError:
state.args.append(args.pop(0)) state.args.append(args.pop(0))
@ -303,7 +303,7 @@ def getId(irc, msg, args, state, kind=None):
try: try:
args[0] = args[0].lstrip('#') args[0] = args[0].lstrip('#')
getInt(irc, msg, args, state, type=type) getInt(irc, msg, args, state, type=type)
except Exception as e: except Exception:
args[0] = original args[0] = original
raise raise
@ -398,9 +398,9 @@ def getHostmask(irc, msg, args, state):
def getBanmask(irc, msg, args, state): def getBanmask(irc, msg, args, state):
getHostmask(irc, msg, args, state) getHostmask(irc, msg, args, state)
getChannel(irc, msg, args, state) getChannel(irc, msg, args, state)
channel = state.channel
banmaskstyle = conf.supybot.protocols.irc.banmask banmaskstyle = conf.supybot.protocols.irc.banmask
state.args[-1] = banmaskstyle.makeBanmask(state.args[-1]) state.args[-1] = banmaskstyle.makeBanmask(state.args[-1],
channel=state.channel)
def getUser(irc, msg, args, state): def getUser(irc, msg, args, state):
try: try:
@ -431,7 +431,7 @@ def _getRe(f):
s = args.pop(0) s = args.pop(0)
def isRe(s): def isRe(s):
try: try:
foo = f(s) f(s)
return True return True
except ValueError: except ValueError:
return False return False
@ -466,7 +466,7 @@ def getNick(irc, msg, args, state):
def getSeenNick(irc, msg, args, state, errmsg=None): def getSeenNick(irc, msg, args, state, errmsg=None):
try: try:
foo = irc.state.nickToHostmask(args[0]) irc.state.nickToHostmask(args[0])
state.args.append(args.pop(0)) state.args.append(args.pop(0))
except KeyError: except KeyError:
if errmsg is None: if errmsg is None:
@ -850,7 +850,7 @@ class rest(context):
args[:] = [' '.join(args)] args[:] = [' '.join(args)]
try: try:
super(rest, self).__call__(irc, msg, args, state) super(rest, self).__call__(irc, msg, args, state)
except Exception as e: except Exception:
args[:] = original args[:] = original
else: else:
raise IndexError raise IndexError
@ -954,7 +954,7 @@ class commalist(context):
if part: # trailing commas if part: # trailing commas
super(commalist, self).__call__(irc, msg, [part], st) super(commalist, self).__call__(irc, msg, [part], st)
state.args.append(st.args) state.args.append(st.args)
except Exception as e: except Exception:
args[:] = original args[:] = original
raise raise

View File

@ -307,7 +307,7 @@ def registerNetwork(name, password='', ssl=False, sasl_username='',
_("""Determines what password will be used on %s. Yes, we know that _("""Determines what password will be used on %s. Yes, we know that
technically passwords are server-specific and not network-specific, technically passwords are server-specific and not network-specific,
but this is the best we can do right now.""") % name, private=True)) but this is the best we can do right now.""") % name, private=True))
registryServers = registerGlobalValue(network, 'servers', Servers([], registerGlobalValue(network, 'servers', Servers([],
_("""Space-separated list of servers the bot will connect to for %s. _("""Space-separated list of servers the bot will connect to for %s.
Each will be tried in order, wrapping back to the first when the cycle Each will be tried in order, wrapping back to the first when the cycle
is completed.""") % name)) is completed.""") % name))

View File

@ -142,7 +142,7 @@ class DirMapping(MappingInterface):
def remove(self, id): def remove(self, id):
try: try:
os.remove(self._makeFilename(id)) os.remove(self._makeFilename(id))
except EnvironmentError as e: except EnvironmentError:
raise NoRecordError(id) raise NoRecordError(id)
class FlatfileMapping(MappingInterface): class FlatfileMapping(MappingInterface):

View File

@ -35,15 +35,13 @@ Contains simple socket drivers. Asyncore bugged (haha, pun!) me.
from __future__ import division from __future__ import division
import os import os
import sys
import time import time
import errno import errno
import select import select
import socket import socket
from .. import (conf, drivers, log, schedule, utils, world) from .. import (conf, drivers, log, utils, world)
from ..utils import minisix from ..utils import minisix
from ..utils.iter import imap
from ..utils.str import decode_raw_line from ..utils.str import decode_raw_line
try: try:
@ -241,7 +239,6 @@ class SocketDriver(drivers.IrcDriver, drivers.ServersMixin):
server = self._getNextServer() server = self._getNextServer()
socks_proxy = getattr(conf.supybot.networks, self.irc.network) \ socks_proxy = getattr(conf.supybot.networks, self.irc.network) \
.socksproxy() .socksproxy()
resolver = None
try: try:
if socks_proxy: if socks_proxy:
import socks import socks

View File

@ -28,7 +28,7 @@
# POSSIBILITY OF SUCH DAMAGE. # POSSIBILITY OF SUCH DAMAGE.
### ###
from .. import conf, drivers, ircmsgs, log from .. import conf, drivers
from twisted.names import client from twisted.names import client
from twisted.internet import reactor, error from twisted.internet import reactor, error

View File

@ -32,8 +32,6 @@
Contains various drivers (network, file, and otherwise) for using IRC objects. Contains various drivers (network, file, and otherwise) for using IRC objects.
""" """
import sys
import time
import socket import socket
from .. import conf, ircmsgs, log as supylog, utils from .. import conf, ircmsgs, log as supylog, utils

View File

@ -28,11 +28,9 @@
### ###
import os import os
import traceback
import supybot.log as log import supybot.log as log
import supybot.conf as conf import supybot.conf as conf
import supybot.world as world
try: try:
import gnupg import gnupg

View File

@ -32,7 +32,6 @@ An embedded and centralized HTTP server for Supybot's plugins.
""" """
import os import os
import sys
import cgi import cgi
import socket import socket
from threading import Thread from threading import Thread
@ -389,7 +388,6 @@ class Favicon(SupyHTTPServerCallback):
def doGet(self, handler, path): def doGet(self, handler, path):
response = None response = None
file_path = conf.supybot.servers.http.favicon() file_path = conf.supybot.servers.http.favicon()
found = False
if file_path: if file_path:
try: try:
icon = open(file_path, 'rb') icon = open(file_path, 'rb')
@ -399,12 +397,12 @@ class Favicon(SupyHTTPServerCallback):
finally: finally:
icon.close() icon.close()
if response is not None: if response is not None:
filename = file_path.rsplit(os.sep, 1)[1]
if '.' in filename:
ext = filename.rsplit('.', 1)[1]
else:
ext = 'ico'
# I have no idea why, but this headers are already sent. # I have no idea why, but this headers are already sent.
# filename = file_path.rsplit(os.sep, 1)[1]
# if '.' in filename:
# ext = filename.rsplit('.', 1)[1]
# else:
# ext = 'ico'
# self.send_header('Content-Length', len(response)) # self.send_header('Content-Length', len(response))
# self.send_header('Content-type', 'image/' + ext) # self.send_header('Content-type', 'image/' + ext)
# self.end_headers() # self.end_headers()
@ -461,7 +459,7 @@ def unhook(subdir):
global http_servers global http_servers
assert isinstance(http_servers, list) assert isinstance(http_servers, list)
for server in http_servers: for server in http_servers:
callback = server.unhook(subdir) server.unhook(subdir)
if len(server.callbacks) <= 0 and not configGroup.keepAlive(): if len(server.callbacks) <= 0 and not configGroup.keepAlive():
server.shutdown() server.shutdown()
http_servers.remove(server) http_servers.remove(server)

View File

@ -913,7 +913,7 @@ class IgnoresDB(object):
else: else:
expiration = 0 expiration = 0
self.add(hostmask, expiration) self.add(hostmask, expiration)
except Exception as e: except Exception:
log.error('Invalid line in ignores database: %q', line) log.error('Invalid line in ignores database: %q', line)
fd.close() fd.close()

View File

@ -42,7 +42,7 @@ except ImportError:
from . import conf, ircdb, ircmsgs, ircutils, log, utils, world from . import conf, ircdb, ircmsgs, ircutils, log, utils, world
from .utils.str import rsplit from .utils.str import rsplit
from .utils.iter import chain from .utils.iter import chain
from .utils.structures import queue, smallqueue, RingBuffer from .utils.structures import smallqueue, RingBuffer
### ###
# The base class for a callback to be registered with an Irc object. Shows # The base class for a callback to be registered with an Irc object. Shows
@ -1029,7 +1029,7 @@ class Irc(IrcCommandDispatcher, log.Firewalled):
read()) read())
authstring = base64.b64encode( authstring = base64.b64encode(
private_key.sign(base64.b64decode(msg.args[0].encode()))).decode('utf-8') private_key.sign(base64.b64decode(msg.args[0].encode()))).decode('utf-8')
except (BadDigestError, OSError, ValueError) as e: except (BadDigestError, OSError, ValueError):
authstring = "*" authstring = "*"
self.sendMsg(ircmsgs.IrcMsg(command='AUTHENTICATE', args=(authstring,))) self.sendMsg(ircmsgs.IrcMsg(command='AUTHENTICATE', args=(authstring,)))

View File

@ -36,7 +36,6 @@ object (which, as you'll read later, is quite...full-featured :))
""" """
import re import re
import sys
import time import time
import datetime import datetime
import functools import functools

View File

@ -50,7 +50,7 @@ from . import utils
from .utils import minisix from .utils import minisix
from .version import version from .version import version
from .i18n import PluginInternationalization, internationalizeDocstring from .i18n import PluginInternationalization
_ = PluginInternationalization() _ = PluginInternationalization()
def debug(s, *args): def debug(s, *args):

View File

@ -109,7 +109,7 @@ class StdoutStreamHandler(logging.StreamHandler):
if conf.supybot.log.stdout() and not conf.daemonized: if conf.supybot.log.stdout() and not conf.daemonized:
try: try:
logging.StreamHandler.emit(self, record) logging.StreamHandler.emit(self, record)
except ValueError as e: # Raised if sys.stdout is closed. except ValueError: # Raised if sys.stdout is closed.
self.disable() self.disable()
error('Error logging to stdout. Removing stdout handler.') error('Error logging to stdout. Removing stdout handler.')
exception('Uncaught exception in StdoutStreamHandler:') exception('Uncaught exception in StdoutStreamHandler:')
@ -360,14 +360,14 @@ def firewall(f, errorHandler=None):
def m(self, *args, **kwargs): def m(self, *args, **kwargs):
try: try:
return f(self, *args, **kwargs) return f(self, *args, **kwargs)
except Exception as e: except Exception:
if testing: if testing:
raise raise
logException(self) logException(self)
if errorHandler is not None: if errorHandler is not None:
try: try:
return errorHandler(self, *args, **kwargs) return errorHandler(self, *args, **kwargs)
except Exception as e: except Exception:
logException(self, 'Uncaught exception in errorHandler') logException(self, 'Uncaught exception in errorHandler')
m = utils.python.changeFunctionName(m, f.__name__, f.__doc__) m = utils.python.changeFunctionName(m, f.__name__, f.__doc__)
return m return m

View File

@ -37,7 +37,7 @@ from getpass import getpass as getPass
from . import ansi, utils from . import ansi, utils
from .utils import minisix from .utils import minisix
from supybot.i18n import PluginInternationalization, internationalizeDocstring from supybot.i18n import PluginInternationalization
_ = PluginInternationalization() _ = PluginInternationalization()
useBold = False useBold = False

View File

@ -30,7 +30,6 @@
import re import re
import os import os
import sys
import time import time
import json import json
import codecs import codecs
@ -148,7 +147,7 @@ def close(registry, filename, private=True):
value._name) value._name)
try: try:
lines.append('# Default value: %s\n' % x) lines.append('# Default value: %s\n' % x)
except Exception as e: except Exception:
exception('Exception printing default value of %s:' % exception('Exception printing default value of %s:' %
value._name) value._name)
lines.append('###\n') lines.append('###\n')

View File

@ -139,7 +139,7 @@ class Schedule(drivers.IrcDriver):
f = self.events.pop(name) f = self.events.pop(name)
try: try:
f(*args, **kwargs) f(*args, **kwargs)
except Exception as e: except Exception:
log.exception('Uncaught exception in scheduled function:') log.exception('Uncaught exception in scheduled function:')

View File

@ -231,9 +231,9 @@ class PluginTestCase(SupyTestCase):
MiscModule = plugin.loadPluginModule('Misc') MiscModule = plugin.loadPluginModule('Misc')
OwnerModule = plugin.loadPluginModule('Owner') OwnerModule = plugin.loadPluginModule('Owner')
ConfigModule = plugin.loadPluginModule('Config') ConfigModule = plugin.loadPluginModule('Config')
_ = plugin.loadPluginClass(self.irc, MiscModule) plugin.loadPluginClass(self.irc, MiscModule)
_ = plugin.loadPluginClass(self.irc, OwnerModule) plugin.loadPluginClass(self.irc, OwnerModule)
_ = plugin.loadPluginClass(self.irc, ConfigModule) plugin.loadPluginClass(self.irc, ConfigModule)
if isinstance(self.plugins, str): if isinstance(self.plugins, str):
self.plugins = [self.plugins] self.plugins = [self.plugins]
else: else:
@ -241,7 +241,7 @@ class PluginTestCase(SupyTestCase):
if name not in ('Owner', 'Misc', 'Config'): if name not in ('Owner', 'Misc', 'Config'):
module = plugin.loadPluginModule(name, module = plugin.loadPluginModule(name,
ignoreDeprecation=True) ignoreDeprecation=True)
cb = plugin.loadPluginClass(self.irc, module) plugin.loadPluginClass(self.irc, module)
self.irc.addCallback(TestInstance) self.irc.addCallback(TestInstance)
for (name, value) in self.config.items(): for (name, value) in self.config.items():
group = conf.supybot group = conf.supybot

View File

@ -28,7 +28,6 @@
# POSSIBILITY OF SUCH DAMAGE. # POSSIBILITY OF SUCH DAMAGE.
### ###
import sys
from . import minisix from . import minisix
### ###

View File

@ -27,8 +27,6 @@
# POSSIBILITY OF SUCH DAMAGE. # POSSIBILITY OF SUCH DAMAGE.
### ###
import sys
from hashlib import md5 from hashlib import md5
from hashlib import sha1 as sha from hashlib import sha1 as sha

View File

@ -35,7 +35,6 @@ import shutil
import os.path import os.path
from . import crypt from . import crypt
from .iter import ifilter
def contents(filename): def contents(filename):
with open(filename) as fd: with open(filename) as fd:

View File

@ -33,8 +33,6 @@ from __future__ import print_function
import os import os
import sys import sys
import ast import ast
import time
import types
import textwrap import textwrap
import warnings import warnings
import functools import functools
@ -45,7 +43,6 @@ import collections
from . import crypt from . import crypt
from .str import format from .str import format
from .file import mktemp from .file import mktemp
from .iter import imap
from . import minisix from . import minisix
from . import internationalization as _ from . import internationalization as _
@ -230,24 +227,24 @@ class IterableMap(object):
__iter__ = items __iter__ = items
def keys(self): def keys(self):
for (key, _) in self.items(): for (key, __) in self.items():
yield key yield key
def values(self): def values(self):
for (_, value) in self.items(): for (__, value) in self.items():
yield value yield value
@warn_non_constant_time @warn_non_constant_time
def __len__(self): def __len__(self):
ret = 0 ret = 0
for _ in self.items(): for __ in self.items():
ret += 1 ret += 1
return ret return ret
@warn_non_constant_time @warn_non_constant_time
def __bool__(self): def __bool__(self):
for _ in self.items(): for __ in self.items():
return True return True
return False return False
__nonzero__ = __bool__ __nonzero__ = __bool__
@ -300,7 +297,7 @@ class InsensitivePreservingDict(collections.MutableMapping):
def keys(self): def keys(self):
L = [] L = []
for (k, _) in self.items(): for (k, __) in self.items():
L.append(k) L.append(k)
return L return L
@ -347,7 +344,7 @@ def stackTrace(frame=None, compact=True):
def callTracer(fd=None, basename=True): def callTracer(fd=None, basename=True):
if fd is None: if fd is None:
fd = sys.stdout fd = sys.stdout
def tracer(frame, event, _): def tracer(frame, event, __):
if event == 'call': if event == 'call':
code = frame.f_code code = frame.f_code
lineno = frame.f_lineno lineno = frame.f_lineno

View File

@ -29,7 +29,6 @@
from __future__ import division from __future__ import division
import sys
import random import random
from itertools import * from itertools import *

View File

@ -32,7 +32,6 @@ import sys
import types import types
import fnmatch import fnmatch
import threading import threading
import traceback
def universalImport(*names): def universalImport(*names):
"""Attempt to import the given modules, in order, returning the first """Attempt to import the given modules, in order, returning the first

View File

@ -34,13 +34,12 @@ Simple utility functions related to strings.
""" """
import re import re
import sys
import time import time
import string import string
import textwrap import textwrap
from . import minisix from . import minisix
from .iter import all, any from .iter import any
from .structures import TwoWayDictionary from .structures import TwoWayDictionary
from . import internationalization as _ from . import internationalization as _

View File

@ -32,7 +32,6 @@ Data structures for Python.
""" """
import time import time
import types
import collections import collections

View File

@ -29,7 +29,6 @@
### ###
import re import re
import sys
import base64 import base64
import socket import socket
@ -174,7 +173,7 @@ def getUrl(url, size=None, headers=None, data=None, timeout=None):
text = fd.read() text = fd.read()
else: else:
text = fd.read(size) text = fd.read(size)
except socket.timeout as e: except socket.timeout:
raise Error(TIMED_OUT) raise Error(TIMED_OUT)
fd.close() fd.close()
return text return text