提交 837f6ad6 authored 作者: Arnaud Bergeron's avatar Arnaud Bergeron

Make theano/compat/* pass the flake8 test.

上级 856a3662
"""Code supporting compatibility across versions of Python. """Code supporting compatibility across versions of Python.
""" """
# Python 3.x compatibility # Python 3.x compatibility
...@@ -7,6 +6,9 @@ from theano.compat.six import PY3, b, BytesIO, next, get_unbound_function ...@@ -7,6 +6,9 @@ from theano.compat.six import PY3, b, BytesIO, next, get_unbound_function
from theano.compat.six.moves import configparser from theano.compat.six.moves import configparser
from theano.compat.six.moves import reload_module as reload from theano.compat.six.moves import reload_module as reload
__all__ = ['PY3', 'b', 'BytesIO', 'next', 'get_unbound_function',
'configparser', 'reload']
if PY3: if PY3:
from operator import truediv as operator_div from operator import truediv as operator_div
...@@ -19,9 +21,9 @@ if PY3: ...@@ -19,9 +21,9 @@ if PY3:
return exc_message(msg) return exc_message(msg)
return msg return msg
def cmp(a, b): def cmp(x, y):
"""Return -1 if x < y, 0 if x == y, 1 if x > y.""" """Return -1 if x < y, 0 if x == y, 1 if x > y."""
return (a > b) - (a < b) return (x > y) - (x < y)
from functools import partial from functools import partial
from collections import defaultdict, deque from collections import defaultdict, deque
......
...@@ -127,7 +127,7 @@ if sys.version_info[:2] < (2, 7): ...@@ -127,7 +127,7 @@ if sys.version_info[:2] < (2, 7):
if isinstance(other, OrderedDict): if isinstance(other, OrderedDict):
if len(self) != len(other): if len(self) != len(other):
return False return False
for p, q in zip(self.items(), other.items()): for p, q in zip(self.items(), other.items()):
if p != q: if p != q:
return False return False
return True return True
...@@ -166,25 +166,34 @@ if sys.version_info[:2] < (2, 7): ...@@ -166,25 +166,34 @@ if sys.version_info[:2] < (2, 7):
from itertools import repeat, ifilter from itertools import repeat, ifilter
class Counter(dict): class Counter(dict):
'''Dict subclass for counting hashable objects. Sometimes called a bag '''Dict subclass for counting hashable objects.
or multiset. Elements are stored as dictionary keys and their counts
are stored as dictionary values. Sometimes called a bag or multiset. Elements are stored as
dictionary keys and their counts are stored as dictionary
values.
>>> Counter('zyzygy') >>> Counter('zyzygy')
Counter({'y': 3, 'z': 2, 'g': 1}) Counter({'y': 3, 'z': 2, 'g': 1})
''' '''
def __init__(self, iterable=None, **kwds): def __init__(self, iterable=None, **kwds):
'''Create a new, empty Counter object. And if given, count elements '''Create a new, empty Counter object.
from an input iterable. Or, initialize the count from another mapping
of elements to their counts. And if given, count elements from an input iterable. Or,
initialize the count from another mapping of elements to
their counts.
>>> c = Counter() # a new, empty counter A new, empty counter:
>>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter()
>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
>>> c = Counter(a=4, b=2) # a new counter from keyword args
A new counter from an iterable
>>> c = Counter('gallahad')
A new counter from a mapping
>>> c = Counter({'a': 4, 'b': 2})
A new counter from keyword args
>>> c = Counter(a=4, b=2)
''' '''
self.update(iterable, **kwds) self.update(iterable, **kwds)
...@@ -192,27 +201,30 @@ if sys.version_info[:2] < (2, 7): ...@@ -192,27 +201,30 @@ if sys.version_info[:2] < (2, 7):
return 0 return 0
def most_common(self, n=None): def most_common(self, n=None):
'''List the n most common elements and their counts from the most '''List the n most common elements and their counts.
common to the least. If n is None, then list all element counts.
The list goes from the most common to the least. If n is
None, then list all element counts.
>>> Counter('abracadabra').most_common(3) >>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)] [('a', 5), ('r', 2), ('b', 2)]
''' '''
if n is None: if n is None:
return sorted(self.iteritems(), key=itemgetter(1), reverse=True) return sorted(self.iteritems(), key=itemgetter(1),
reverse=True)
return nlargest(n, self.iteritems(), key=itemgetter(1)) return nlargest(n, self.iteritems(), key=itemgetter(1))
def elements(self): def elements(self):
'''Iterator over elements repeating each as many times as its count. '''Iterator over elements.
It repeats each element as many times as its count.
>>> c = Counter('ABCABC') >>> c = Counter('ABCABC')
>>> sorted(c.elements()) >>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C'] ['A', 'A', 'B', 'B', 'C', 'C']
If an element's count has been set to zero or is a negative number, If an element's count has been set to zero or is a negative
elements() will ignore it. number, elements() will ignore it.
''' '''
for elem, count in self.iteritems(): for elem, count in self.iteritems():
for _ in repeat(None, count): for _ in repeat(None, count):
...@@ -223,20 +235,21 @@ if sys.version_info[:2] < (2, 7): ...@@ -223,20 +235,21 @@ if sys.version_info[:2] < (2, 7):
@classmethod @classmethod
def fromkeys(cls, iterable, v=None): def fromkeys(cls, iterable, v=None):
raise NotImplementedError( raise NotImplementedError(
'Counter.fromkeys() is undefined. Use Counter(iterable) instead.') 'Counter.fromkeys() is undefined. '
'Use Counter(iterable) instead.')
def update(self, iterable=None, **kwds): def update(self, iterable=None, **kwds):
'''Like dict.update() but add counts instead of replacing them. '''Like dict.update() but add counts instead of replacing them.
Source can be an iterable, a dictionary, or another Counter instance. Source can be an iterable, a dictionary, or another Counter
instance.
>>> c = Counter('which') >>> c = Counter('which')
>>> c.update('witch') # add elements from another iterable >>> c.update('witch') # add elements from another iterable
>>> d = Counter('watch') >>> d = Counter('watch')
>>> c.update(d) # add elements from another counter >>> c.update(d) # add elements from another counter
>>> c['h'] # four 'h' in which, witch, and watch >>> c['h'] # four 'h' in which, witch, and watch
4 4
''' '''
if iterable is not None: if iterable is not None:
if hasattr(iterable, 'iteritems'): if hasattr(iterable, 'iteritems'):
...@@ -245,7 +258,8 @@ if sys.version_info[:2] < (2, 7): ...@@ -245,7 +258,8 @@ if sys.version_info[:2] < (2, 7):
for elem, count in iterable.iteritems(): for elem, count in iterable.iteritems():
self[elem] = self_get(elem, 0) + count self[elem] = self_get(elem, 0) + count
else: else:
dict.update(self, iterable) # fast path when counter is empty # fast path when counter is empty
dict.update(self, iterable)
else: else:
self_get = self.get self_get = self.get
for elem in iterable: for elem in iterable:
...@@ -254,11 +268,13 @@ if sys.version_info[:2] < (2, 7): ...@@ -254,11 +268,13 @@ if sys.version_info[:2] < (2, 7):
self.update(kwds) self.update(kwds)
def copy(self): def copy(self):
'Like dict.copy() but returns a Counter instance instead of a dict.' '''Like dict.copy() but returns a Counter instance instead
of a dict.'''
return Counter(self) return Counter(self)
def __delitem__(self, elem): def __delitem__(self, elem):
'Like dict.__delitem__() but does not raise KeyError for missing values.' '''Like dict.__delitem__() but does not raise KeyError for
missing values.'''
if elem in self: if elem in self:
dict.__delitem__(self, elem) dict.__delitem__(self, elem)
...@@ -351,9 +367,7 @@ else: ...@@ -351,9 +367,7 @@ else:
from UserDict import DictMixin from UserDict import DictMixin
except ImportError: except ImportError:
from collections import MutableMapping as DictMixin from collections import MutableMapping as DictMixin
OrderedDict = collections.OrderedDict from collections import OrderedDict, Callable, Counter
from collections import Callable Callable = Callable
from collections import Counter
__all__ += ['DictMixin', 'OrderedDict', 'Counter']
__all__ = ['DictMixin', 'OrderedDict', 'Counter']
...@@ -2,22 +2,23 @@ ...@@ -2,22 +2,23 @@
# Copyright (c) 2010-2012 Benjamin Peterson # Copyright (c) 2010-2012 Benjamin Peterson
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy of # Permission is hereby granted, free of charge, to any person obtaining a copy
# this software and associated documentation files (the "Software"), to deal in # of this software and associated documentation files (the "Software"), to deal
# the Software without restriction, including without limitation the rights to # in the Software without restriction, including without limitation the rights
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# the Software, and to permit persons to whom the Software is furnished to do so, # copies of the Software, and to permit persons to whom the Software is
# subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # The above copyright notice and this permission notice shall be included in
# copies or substantial portions of the Software. # all copies or substantial portions of the Software.
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import operator import operator
import sys import sys
...@@ -151,7 +152,8 @@ _moved_attributes = [ ...@@ -151,7 +152,8 @@ _moved_attributes = [
MovedModule("html_entities", "htmlentitydefs", "html.entities"), MovedModule("html_entities", "htmlentitydefs", "html.entities"),
MovedModule("html_parser", "HTMLParser", "html.parser"), MovedModule("html_parser", "HTMLParser", "html.parser"),
MovedModule("http_client", "httplib", "http.client"), MovedModule("http_client", "httplib", "http.client"),
MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), MovedModule("email_mime_multipart", "email.MIMEMultipart",
"email.mime.multipart"),
MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
...@@ -164,8 +166,10 @@ _moved_attributes = [ ...@@ -164,8 +166,10 @@ _moved_attributes = [
MovedModule("tkinter", "Tkinter"), MovedModule("tkinter", "Tkinter"),
MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), MovedModule("tkinter_scrolledtext", "ScrolledText",
MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), "tkinter.scrolledtext"),
MovedModule("tkinter_simpledialog", "SimpleDialog",
"tkinter.simpledialog"),
MovedModule("tkinter_tix", "Tix", "tkinter.tix"), MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
...@@ -289,8 +293,10 @@ def iteritems(d): ...@@ -289,8 +293,10 @@ def iteritems(d):
if PY3: if PY3:
def b(s): def b(s):
return s.encode("latin-1") return s.encode("latin-1")
def u(s): def u(s):
return s return s
if sys.version_info[1] <= 1: if sys.version_info[1] <= 1:
def int2byte(i): def int2byte(i):
return bytes((i,)) return bytes((i,))
...@@ -303,8 +309,10 @@ if PY3: ...@@ -303,8 +309,10 @@ if PY3:
else: else:
def b(s): def b(s):
return s return s
def u(s): def u(s):
return unicode(s, "unicode_escape") return unicode(s, "unicode_escape")
int2byte = chr int2byte = chr
import StringIO import StringIO
StringIO = BytesIO = StringIO.StringIO StringIO = BytesIO = StringIO.StringIO
...@@ -346,6 +354,7 @@ else: ...@@ -346,6 +354,7 @@ else:
fp = kwargs.pop("file", sys.stdout) fp = kwargs.pop("file", sys.stdout)
if fp is None: if fp is None:
return return
def write(data): def write(data):
if not isinstance(data, basestring): if not isinstance(data, basestring):
data = str(data) data = str(data)
......
...@@ -19,9 +19,6 @@ except ImportError: ...@@ -19,9 +19,6 @@ except ImportError:
whitelist_flake8 = [ whitelist_flake8 = [
"__init__.py", "__init__.py",
"version.py", "version.py",
"compat/python2x.py",
"compat/six.py",
"compat/__init__.py",
"tests/test_gradient.py", "tests/test_gradient.py",
"tests/test_config.py", "tests/test_config.py",
"tests/diverse_tests.py", "tests/diverse_tests.py",
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论