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

Make theano/compat/* pass the flake8 test.

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