pep8 fixes, modernizations

autopep8 -a -r -i --select E711,E712,W601,W602,W603,W604,W690,E304,E401,E502 .
Also includes some manual reindentations (many are left after the print()
changes).
Manually checked, some modernizations not commited here.
This commit is contained in:
Laurent Bachelier 2014-10-10 22:10:41 +02:00
commit 6161a0aacd
18 changed files with 57 additions and 51 deletions

View file

@ -30,7 +30,9 @@ from weboob.core import Weboob
from weboob.capabilities.video import CapVideo from weboob.capabilities.video import CapVideo
# hack to workaround bash redirection and encoding problem # hack to workaround bash redirection and encoding problem
import sys, codecs, locale import sys
import codecs
import locale
if sys.stdout.encoding is None: if sys.stdout.encoding is None:
(lang, enc) = locale.getdefaultlocale() (lang, enc) = locale.getdefaultlocale()

View file

@ -102,17 +102,17 @@ class BoobankMuninPlugin(object):
if check and (last + self.cache_expire) < time.time(): if check and (last + self.cache_expire) < time.time():
return False return False
for line in f.xreadlines(): for line in f:
sys.stdout.write(line) sys.stdout.write(line)
return True return True
def new_cache(self, name): def new_cache(self, name):
os.umask(0077) os.umask(0o077)
new_name = '%s.new' % name new_name = '%s.new' % name
filename = self.cachepath(new_name) filename = self.cachepath(new_name)
try: try:
f = open(filename, 'w') f = open(filename, 'w')
except IOError, e: except IOError as e:
print >>sys.stderr, 'Unable to create the cache file %s: %s' % (filename, e) print >>sys.stderr, 'Unable to create the cache file %s: %s' % (filename, e)
return return
@ -166,7 +166,7 @@ class BoobankMuninPlugin(object):
self.write_output('%s.label %s' % (id, account.label.encode('iso-8859-15'))) self.write_output('%s.label %s' % (id, account.label.encode('iso-8859-15')))
if self.cumulate: if self.cumulate:
self.write_output('%s.draw %s' % (id, type)) self.write_output('%s.draw %s' % (id, type))
except CallErrors, errors: except CallErrors as errors:
self.print_errors(errors) self.print_errors(errors)
self.print_cache('boobank-munin-config') self.print_cache('boobank-munin-config')
else: else:
@ -197,7 +197,7 @@ class BoobankMuninPlugin(object):
if account.coming and self.add_coming: if account.coming and self.add_coming:
balance += account.coming balance += account.coming
self.write_output('%s.value %d' % (self.account2id(account), balance)) self.write_output('%s.value %d' % (self.account2id(account), balance))
except CallErrors, errors: except CallErrors as errors:
self.print_errors(errors) self.print_errors(errors)
self.print_cache('boobank-munin') self.print_cache('boobank-munin')
else: else:

View file

@ -191,17 +191,17 @@ class GenericMuninPlugin(object):
if check and (last + self.cache_expire) < time.time(): if check and (last + self.cache_expire) < time.time():
return False return False
for line in f.xreadlines(): for line in f:
sys.stdout.write(line) sys.stdout.write(line)
return True return True
def new_cache(self, name): def new_cache(self, name):
os.umask(0077) os.umask(0o077)
new_name = '%s.new' % name new_name = '%s.new' % name
filename = self.cachepath(new_name) filename = self.cachepath(new_name)
try: try:
f = open(filename, 'w') f = open(filename, 'w')
except IOError, e: except IOError as e:
print >>sys.stderr, 'Unable to create the cache file %s: %s' % (filename, e) print >>sys.stderr, 'Unable to create the cache file %s: %s' % (filename, e)
return return
@ -310,7 +310,7 @@ class GenericMuninPlugin(object):
self.write_output('%s.label %s' % (id.encode('iso-8859-15'), getattr(result, self.attriblabel).encode('iso-8859-15'))) self.write_output('%s.label %s' % (id.encode('iso-8859-15'), getattr(result, self.attriblabel).encode('iso-8859-15')))
if self.cumulate: if self.cumulate:
self.write_output('%s.draw %s' % (id, type)) self.write_output('%s.draw %s' % (id, type))
except CallErrors, errors: except CallErrors as errors:
self.print_errors(errors) self.print_errors(errors)
self.print_cache('%s-config' % self.name) self.print_cache('%s-config' % self.name)
else: else:
@ -334,7 +334,7 @@ class GenericMuninPlugin(object):
value = self.get_value(result) value = self.get_value(result)
if value is not NotAvailable: if value is not NotAvailable:
self.write_output('%s.value %f' % (self.result2id(result).encode('iso-8859-15'), value)) self.write_output('%s.value %f' % (self.result2id(result).encode('iso-8859-15'), value))
except CallErrors, errors: except CallErrors as errors:
self.print_errors(errors) self.print_errors(errors)
self.print_cache(self.name) self.print_cache(self.name)
else: else:

View file

@ -11,7 +11,8 @@
# All configuration values have a default; values that are commented out # All configuration values have a default; values that are commented out
# serve to show the default. # serve to show the default.
import os, time import os
import time
os.system('./genapi.py') os.system('./genapi.py')

View file

@ -142,7 +142,7 @@ class RoadmapPage(Page):
if len(current_step['line']) > 0 and \ if len(current_step['line']) > 0 and \
len(current_step['departure']) > 0 and \ len(current_step['departure']) > 0 and \
len(current_step['arrival']) > 0: len(current_step['arrival']) > 0:
current_step['line'] = to_unicode("%s : %s" % \ current_step['line'] = to_unicode("%s : %s" %
(current_step['mode'], current_step['line'])) (current_step['mode'], current_step['line']))
del current_step['mode'] del current_step['mode']
yield current_step yield current_step

View file

@ -26,7 +26,8 @@ from weboob.tools.backend import Module, BackendConfig
from .browser import NolifeTVBrowser from .browser import NolifeTVBrowser
from .video import NolifeTVVideo from .video import NolifeTVVideo
import urllib, time import urllib
import time
from hashlib import md5 from hashlib import md5
__all__ = ['NolifeTVModule'] __all__ = ['NolifeTVModule']

View file

@ -69,7 +69,7 @@ class VideoPage(Page):
class VideoListPage(Page): class VideoListPage(Page):
def is_list_empty(self): def is_list_empty(self):
return self.document.getroot() == None return self.document.getroot() is None
def iter_video(self, available_videos): def iter_video(self, available_videos):
for el in self.document.getroot().xpath('//li/a'): for el in self.document.getroot().xpath('//li/a'):
@ -101,7 +101,7 @@ class FamilyPage(Page):
while True: while True:
el = el.getnext() el = el.getnext()
if el == None or el.get('data-role'): if el is None or el.get('data-role'):
break break
h1 = el.find('.//h1') h1 = el.find('.//h1')
id = h1.getparent().attrib['href'] id = h1.getparent().attrib['href']

View file

@ -2,9 +2,9 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import print_function from __future__ import print_function
import os
import subprocess import subprocess
import sys import sys
import os
if '--deps' in sys.argv: if '--deps' in sys.argv:
sys.argv.remove('--deps') sys.argv.remove('--deps')
@ -25,8 +25,8 @@ if len(sys.argv) < 2:
print("To install all the missing dependencies, add the option --deps") print("To install all the missing dependencies, add the option --deps")
print("at the end of the command line.") print("at the end of the command line.")
print() print()
print("Error: Please provide a destination, " \ print("Error: Please provide a destination, "
"for example %s/bin" % os.getenv('HOME'), file=sys.stderr) "for example %s/bin" % os.getenv('HOME'), file=sys.stderr)
sys.exit(1) sys.exit(1)
else: else:
dest = os.path.expanduser(sys.argv[1]) dest = os.path.expanduser(sys.argv[1])

View file

@ -2,6 +2,17 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import print_function from __future__ import print_function
import imp
import inspect
import optparse
import os
import re
import sys
import tempfile
import time
from weboob.tools.application.base import Application
# Copyright(C) 2010-2011 Laurent Bachelier # Copyright(C) 2010-2011 Laurent Bachelier
# #
# This file is part of weboob. # This file is part of weboob.
@ -19,16 +30,6 @@ from __future__ import print_function
# You should have received a copy of the GNU Affero General Public License # You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>. # along with weboob. If not, see <http://www.gnu.org/licenses/>.
import sys
import os
import tempfile
import imp
import inspect
import optparse
import re
import time
from weboob.tools.application.base import Application
BASE_PATH = os.path.join(os.path.dirname(__file__), os.pardir) BASE_PATH = os.path.join(os.path.dirname(__file__), os.pardir)
DEST_DIR = 'man' DEST_DIR = 'man'
@ -121,8 +122,8 @@ def main():
try: try:
script = imp.load_module("scripts.%s" % fname, f, tmpfile, desc) script = imp.load_module("scripts.%s" % fname, f, tmpfile, desc)
except ImportError as e: except ImportError as e:
print("Unable to load the %s script (%s)" \ print("Unable to load the %s script (%s)"
% (fname, e), file=sys.stderr) % (fname, e), file=sys.stderr)
else: else:
print("Loaded %s" % fname) print("Loaded %s" % fname)
# Find the applications we can handle # Find the applications we can handle

View file

@ -19,7 +19,8 @@
from __future__ import print_function from __future__ import print_function
import datetime, uuid import datetime
import uuid
from dateutil.relativedelta import relativedelta from dateutil.relativedelta import relativedelta
from dateutil.parser import parse as parse_date from dateutil.parser import parse as parse_date
from decimal import Decimal, InvalidOperation from decimal import Decimal, InvalidOperation
@ -334,8 +335,8 @@ class Boobank(ReplApplication):
try: try:
end_date = parse_date(end_date) end_date = parse_date(end_date)
except ValueError: except ValueError:
print('"%s" is an incorrect date format (for example "%s")' % \ print('"%s" is an incorrect date format (for example "%s")' %
(end_date, (datetime.date.today() - relativedelta(months=1)).strftime('%Y-%m-%d')), file=self.stderr) (end_date, (datetime.date.today() - relativedelta(months=1)).strftime('%Y-%m-%d')), file=self.stderr)
return 3 return 3
old_count = self.options.count old_count = self.options.count
self.options.count = None self.options.count = None

View file

@ -424,7 +424,7 @@ class Cineoob(ReplApplication):
self.start_format() self.start_format()
self.format(movie) self.format(movie)
#================== TORRENT ================== # ================== TORRENT ==================
def complete_info_torrent(self, text, line, *ignored): def complete_info_torrent(self, text, line, *ignored):
args = line.split(' ') args = line.split(' ')
@ -484,9 +484,9 @@ class Cineoob(ReplApplication):
except CallErrors as errors: except CallErrors as errors:
for backend, error, backtrace in errors: for backend, error, backtrace in errors:
if isinstance(error, MagnetOnly): if isinstance(error, MagnetOnly):
print(u'Error(%s): No direct URL available, ' \ print(u'Error(%s): No direct URL available, '
u'please provide this magnet URL ' \ u'please provide this magnet URL '
u'to your client:\n%s' % (backend, error.magnet), file=self.stderr) u'to your client:\n%s' % (backend, error.magnet), file=self.stderr)
return 4 return 4
else: else:
self.bcall_error_handler(backend, error, backtrace) self.bcall_error_handler(backend, error, backtrace)
@ -531,7 +531,7 @@ class Cineoob(ReplApplication):
for torrent in self.do('iter_torrents', pattern=pattern, caps=CapTorrent): for torrent in self.do('iter_torrents', pattern=pattern, caps=CapTorrent):
self.cached_format(torrent) self.cached_format(torrent)
#================== SUBTITLE ================== # ================== SUBTITLE ==================
def complete_info_subtitle(self, text, line, *ignored): def complete_info_subtitle(self, text, line, *ignored):
args = line.split(' ') args = line.split(' ')

View file

@ -162,9 +162,9 @@ class Weboorrents(ReplApplication):
except CallErrors as errors: except CallErrors as errors:
for backend, error, backtrace in errors: for backend, error, backtrace in errors:
if isinstance(error, MagnetOnly): if isinstance(error, MagnetOnly):
print(u'Error(%s): No direct URL available, ' \ print(u'Error(%s): No direct URL available, '
u'please provide this magnet URL ' \ u'please provide this magnet URL '
u'to your client:\n%s' % (backend, error.magnet), file=self.stderr) u'to your client:\n%s' % (backend, error.magnet), file=self.stderr)
return 4 return 4
else: else:
self.bcall_error_handler(backend, error, backtrace) self.bcall_error_handler(backend, error, backtrace)

View file

@ -207,7 +207,7 @@ class _ItemElementMeta(type):
filters = [(re.sub('^obj_', '', attr_name), attrs[attr_name]) for attr_name, obj in attrs.items() if attr_name.startswith('obj_')] filters = [(re.sub('^obj_', '', attr_name), attrs[attr_name]) for attr_name, obj in attrs.items() if attr_name.startswith('obj_')]
# constants first, then filters, then methods # constants first, then filters, then methods
filters.sort(key=lambda x: x[1]._creation_counter if hasattr(x[1], '_creation_counter') else (sys.maxint if callable(x[1]) else 0)) filters.sort(key=lambda x: x[1]._creation_counter if hasattr(x[1], '_creation_counter') else (sys.maxsize if callable(x[1]) else 0))
new_class = super(_ItemElementMeta, mcs).__new__(mcs, name, bases, attrs) new_class = super(_ItemElementMeta, mcs).__new__(mcs, name, bases, attrs)
new_class._attrs = _attrs + [f[0] for f in filters] new_class._attrs = _attrs + [f[0] for f in filters]

View file

@ -520,7 +520,7 @@ class ConsoleApplication(Application):
text = f.read() text = f.read()
else: else:
if self.stdin.isatty(): if self.stdin.isatty():
print('Reading content from stdin... Type ctrl-D ' \ print('Reading content from stdin... Type ctrl-D '
'from an empty line to stop.') 'from an empty line to stop.')
text = self.stdin.read() text = self.stdin.read()
return text.decode(self.encoding) return text.decode(self.encoding)

View file

@ -204,7 +204,7 @@ class ReplApplication(Cmd, ConsoleApplication):
print('This command works with an unique backend. Availables:') print('This command works with an unique backend. Availables:')
for index, (name, backend) in enumerate(e.backends): for index, (name, backend) in enumerate(e.backends):
print('%s%d)%s %s%-15s%s %s' % (self.BOLD, index + 1, self.NC, self.BOLD, name, self.NC, print('%s%d)%s %s%-15s%s %s' % (self.BOLD, index + 1, self.NC, self.BOLD, name, self.NC,
backend.DESCRIPTION)) backend.DESCRIPTION))
i = self.ask('Select a backend to proceed with "%s"' % id) i = self.ask('Select a backend to proceed with "%s"' % id)
if not i.isdigit(): if not i.isdigit():
if not i in dict(e.backends): if not i in dict(e.backends):
@ -925,8 +925,8 @@ class ReplApplication(Cmd, ConsoleApplication):
self.commands_formatters = {} self.commands_formatters = {}
self.DEFAULT_FORMATTER = self.set_formatter(args[0]) self.DEFAULT_FORMATTER = self.set_formatter(args[0])
else: else:
print('Formatter "%s" is not available.\n' \ print('Formatter "%s" is not available.\n'
'Available formatters: %s.' % (args[0], ', '.join(self.formatters_loader.get_available_formatters())), file=self.stderr) 'Available formatters: %s.' % (args[0], ', '.join(self.formatters_loader.get_available_formatters())), file=self.stderr)
return 1 return 1
else: else:
print('Default formatter: %s' % self.DEFAULT_FORMATTER) print('Default formatter: %s' % self.DEFAULT_FORMATTER)

View file

@ -66,7 +66,7 @@ def image_mime(data_base64, supported_formats=('gif', 'jpeg', 'png')):
return 'image/x-xcf' return 'image/x-xcf'
elif 'pdf' in supported_formats and '%PDF' in beginning: elif 'pdf' in supported_formats and '%PDF' in beginning:
return 'application/pdf' return 'application/pdf'
elif 'tiff' in supported_formats and ('II\x00\x2a' in beginning or \ elif 'tiff' in supported_formats and ('II\x00\x2a' in beginning or
'MM\x2a\x00' in beginning): 'MM\x2a\x00' in beginning):
return 'image/tiff' return 'image/tiff'

View file

@ -222,9 +222,9 @@ class GridVirtKeyboard(VirtKeyboard):
tileW = float(self.width) / cols tileW = float(self.width) / cols
tileH = float(self.height) / rows tileH = float(self.height) / rows
positions = ((s, i * tileW % self.width, i / cols * tileH) \ positions = ((s, i * tileW % self.width, i / cols * tileH)
for i, s in enumerate(symbols)) for i, s in enumerate(symbols))
coords = dict((s, tuple(map(int, (x, y, x + tileW, y + tileH)))) \ coords = dict((s, tuple(map(int, (x, y, x + tileW, y + tileH))))
for (s, x, y) in positions) for (s, x, y) in positions)
super(GridVirtKeyboard, self).__init__() super(GridVirtKeyboard, self).__init__()