Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Correct flake8 E302 violations

  • Loading branch information...
commit e2ae8b048e7198428f696375b8bdcd89e90002d1 1 parent 3bc0d46
Ray Ashman authored November 02, 2013
39  django/test/_doctest.py
@@ -144,6 +144,8 @@ def patched_isclass(obj):
144 144
 # Option constants.
145 145
 
146 146
 OPTIONFLAGS_BY_NAME = {}
  147
+
  148
+
147 149
 def register_optionflag(name):
148 150
     # Create a new flag unless `name` is already known.
149 151
     return OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(OPTIONFLAGS_BY_NAME))
@@ -194,6 +196,7 @@ def register_optionflag(name):
194 196
 ## 1. Utility Functions
195 197
 ######################################################################
196 198
 
  199
+
197 200
 def _extract_future_flags(globs):
198 201
     """
199 202
     Return the compiler-flags associated with the future features that
@@ -206,6 +209,7 @@ def _extract_future_flags(globs):
206 209
             flags |= feature.compiler_flag
207 210
     return flags
208 211
 
  212
+
209 213
 def _normalize_module(module, depth=2):
210 214
     """
211 215
     Return the module specified by `module`.  In particular:
@@ -225,6 +229,7 @@ def _normalize_module(module, depth=2):
225 229
     else:
226 230
         raise TypeError("Expected a module, string, or None")
227 231
 
  232
+
228 233
 def _load_testfile(filename, package, module_relative):
229 234
     if module_relative:
230 235
         package = _normalize_module(package, 3)
@@ -238,6 +243,7 @@ def _load_testfile(filename, package, module_relative):
238 243
     with open(filename) as fp:
239 244
         return fp.read(), filename
240 245
 
  246
+
241 247
 def _indent(s, indent=4):
242 248
     """
243 249
     Add the given number of space characters to the beginning every
@@ -246,6 +252,7 @@ def _indent(s, indent=4):
246 252
     # This regexp matches the start of non-blank lines:
247 253
     return re.sub('(?m)^(?!$)', indent*' ', s)
248 254
 
  255
+
249 256
 def _exception_traceback(exc_info):
250 257
     """
251 258
     Return a string containing a traceback message for the given
@@ -257,6 +264,7 @@ def _exception_traceback(exc_info):
257 264
     traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
258 265
     return excout.getvalue()
259 266
 
  267
+
260 268
 # Override some StringIO methods.
261 269
 class _SpoofOut(StringIO):
262 270
     def getvalue(self):
@@ -277,6 +285,7 @@ def truncate(self,   size=None):
277 285
         if hasattr(self, "softspace"):
278 286
             del self.softspace
279 287
 
  288
+
280 289
 # Worst-case linear-time ellipsis matching.
281 290
 def _ellipsis_match(want, got):
282 291
     """
@@ -327,6 +336,7 @@ def _ellipsis_match(want, got):
327 336
 
328 337
     return True
329 338
 
  339
+
330 340
 def _comment_line(line):
331 341
     "Return a commented form of the given line"
332 342
     line = line.rstrip()
@@ -335,6 +345,7 @@ def _comment_line(line):
335 345
     else:
336 346
         return '#'
337 347
 
  348
+
338 349
 class _OutputRedirectingPdb(pdb.Pdb):
339 350
     """
340 351
     A specialized version of the python debugger that redirects stdout
@@ -368,6 +379,7 @@ def trace_dispatch(self, *args):
368 379
         finally:
369 380
             sys.stdout = save_stdout
370 381
 
  382
+
371 383
 # [XX] Normalize with respect to os.path.pardir?
372 384
 def _module_relative_path(module, path):
373 385
     if not inspect.ismodule(module):
@@ -405,6 +417,7 @@ def _module_relative_path(module, path):
405 417
 ##   a string (such as an object's docstring).  The DocTest class also
406 418
 ##   includes information about where the string was extracted from.
407 419
 
  420
+
408 421
 class Example:
409 422
     """
410 423
     A single doctest example, consisting of source code and expected
@@ -458,6 +471,7 @@ def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
458 471
         self.options = options
459 472
         self.exc_msg = exc_msg
460 473
 
  474
+
461 475
 class DocTest:
462 476
     """
463 477
     A collection of doctest examples that should be run in a single
@@ -506,10 +520,10 @@ def __repr__(self):
506 520
         return ('<DocTest %s from %s:%s (%s)>' %
507 521
                 (self.name, self.filename, self.lineno, examples))
508 522
 
509  
-
510 523
     # This lets us sort tests by name:
511 524
     def _cmpkey(self):
512 525
         return (self.name, self.filename, self.lineno, id(self))
  526
+
513 527
     def __cmp__(self, other):
514 528
         if not isinstance(other, DocTest):
515 529
             return -1
@@ -1054,6 +1068,7 @@ def _find_lineno(self, obj, source_lines):
1054 1068
 ## 5. DocTest Runner
1055 1069
 ######################################################################
1056 1070
 
  1071
+
1057 1072
 class DocTestRunner:
1058 1073
     """
1059 1074
     A class used to run DocTest test cases, and accumulate statistics.
@@ -1408,6 +1423,7 @@ def __record_outcome(self, test, f, t):
1408 1423
     __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
1409 1424
                                          r'(?P<name>[\w\.]+)'
1410 1425
                                          r'\[(?P<examplenum>\d+)\]>$')
  1426
+
1411 1427
     def __patched_linecache_getlines(self, filename, module_globals=None):
1412 1428
         m = self.__LINECACHE_FILENAME_RE.match(filename)
1413 1429
         if m and m.group('name') == self.test.name:
@@ -1541,6 +1557,7 @@ def merge(self, other):
1541 1557
                 t = t + t2
1542 1558
             d[name] = f, t
1543 1559
 
  1560
+
1544 1561
 class OutputChecker:
1545 1562
     """
1546 1563
     A class used to check the whether the actual output from a doctest
@@ -1674,6 +1691,7 @@ def output_difference(self, example, got, optionflags):
1674 1691
         else:
1675 1692
             return 'Expected nothing\nGot nothing\n'
1676 1693
 
  1694
+
1677 1695
 class DocTestFailure(Exception):
1678 1696
     """A DocTest example has failed in debugging mode.
1679 1697
 
@@ -1693,6 +1711,7 @@ def __init__(self, test, example, got):
1693 1711
     def __str__(self):
1694 1712
         return str(self.test)
1695 1713
 
  1714
+
1696 1715
 class UnexpectedException(Exception):
1697 1716
     """A DocTest example has encountered an unexpected exception
1698 1717
 
@@ -1712,6 +1731,7 @@ def __init__(self, test, example, exc_info):
1712 1731
     def __str__(self):
1713 1732
         return str(self.test)
1714 1733
 
  1734
+
1715 1735
 class DebugRunner(DocTestRunner):
1716 1736
     r"""Run doc tests but raise an exception as soon as there is a failure.
1717 1737
 
@@ -1824,6 +1844,7 @@ def report_failure(self, out, test, example, got):
1824 1844
 # class, updated by testmod.
1825 1845
 master = None
1826 1846
 
  1847
+
1827 1848
 def testmod(m=None, name=None, globs=None, verbose=None,
1828 1849
             report=True, optionflags=0, extraglobs=None,
1829 1850
             raise_on_error=False, exclude_empty=False):
@@ -1928,6 +1949,7 @@ class doctest.Tester, then merges the results into (or creates)
1928 1949
 
1929 1950
     return runner.failures, runner.tries
1930 1951
 
  1952
+
1931 1953
 def testfile(filename, module_relative=True, name=None, package=None,
1932 1954
              globs=None, verbose=None, report=True, optionflags=0,
1933 1955
              extraglobs=None, raise_on_error=False, parser=DocTestParser(),
@@ -2051,6 +2073,7 @@ class doctest.Tester, then merges the results into (or creates)
2051 2073
 
2052 2074
     return runner.failures, runner.tries
2053 2075
 
  2076
+
2054 2077
 def run_docstring_examples(f, globs, verbose=False, name="NoName",
2055 2078
                            compileflags=None, optionflags=0):
2056 2079
     """
@@ -2080,6 +2103,7 @@ def run_docstring_examples(f, globs, verbose=False, name="NoName",
2080 2103
 # This is provided only for backwards compatibility.  It's not
2081 2104
 # actually used in any way.
2082 2105
 
  2106
+
2083 2107
 class Tester:
2084 2108
     def __init__(self, mod=None, globs=None, verbose=None, optionflags=0):
2085 2109
 
@@ -2145,6 +2169,7 @@ def merge(self, other):
2145 2169
 
2146 2170
 _unittest_reportflags = 0
2147 2171
 
  2172
+
2148 2173
 def set_unittest_reportflags(flags):
2149 2174
     """Sets the unittest option flags.
2150 2175
 
@@ -2328,6 +2353,7 @@ def __repr__(self):
2328 2353
     def shortDescription(self):
2329 2354
         return "Doctest: " + self._dt_test.name
2330 2355
 
  2356
+
2331 2357
 def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
2332 2358
                  test_class=DocTestCase, **options):
2333 2359
     """
@@ -2391,6 +2417,7 @@ def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
2391 2417
 
2392 2418
     return suite
2393 2419
 
  2420
+
2394 2421
 class DocFileCase(DocTestCase):
2395 2422
 
2396 2423
     def id(self):
@@ -2405,6 +2432,7 @@ def format_failure(self, err):
2405 2432
                 % (self._dt_test.name, self._dt_test.filename, err)
2406 2433
                 )
2407 2434
 
  2435
+
2408 2436
 def DocFileTest(path, module_relative=True, package=None,
2409 2437
                 globs=None, parser=DocTestParser(),
2410 2438
                 encoding=None, **options):
@@ -2434,6 +2462,7 @@ def DocFileTest(path, module_relative=True, package=None,
2434 2462
     test = parser.get_doctest(doc, globs, name, path, 0)
2435 2463
     return DocFileCase(test, **options)
2436 2464
 
  2465
+
2437 2466
 def DocFileSuite(*paths, **kw):
2438 2467
     """A unittest suite for one or more doctest files.
2439 2468
 
@@ -2507,6 +2536,7 @@ def DocFileSuite(*paths, **kw):
2507 2536
 ## 9. Debugging Support
2508 2537
 ######################################################################
2509 2538
 
  2539
+
2510 2540
 def script_from_examples(s):
2511 2541
     r"""Extract script from text with examples.
2512 2542
 
@@ -2587,6 +2617,7 @@ def script_from_examples(s):
2587 2617
     # Combine the output, and return it.
2588 2618
     return '\n'.join(output)
2589 2619
 
  2620
+
2590 2621
 def testsource(module, name):
2591 2622
     """Extract the test sources from a doctest docstring as a script.
2592 2623
 
@@ -2603,11 +2634,13 @@ def testsource(module, name):
2603 2634
     testsrc = script_from_examples(test.docstring)
2604 2635
     return testsrc
2605 2636
 
  2637
+
2606 2638
 def debug_src(src, pm=False, globs=None):
2607 2639
     """Debug a single doctest docstring, in argument `src`'"""
2608 2640
     testsrc = script_from_examples(src)
2609 2641
     debug_script(testsrc, pm, globs)
2610 2642
 
  2643
+
2611 2644
 def debug_script(src, pm=False, globs=None):
2612 2645
     "Debug a test script.  `src` is the script, as a string."
2613 2646
     import pdb
@@ -2639,6 +2672,7 @@ def debug_script(src, pm=False, globs=None):
2639 2672
     finally:
2640 2673
         os.remove(srcfilename)
2641 2674
 
  2675
+
2642 2676
 def debug(module, name, pm=False):
2643 2677
     """Debug a single doctest docstring.
2644 2678
 
@@ -2653,6 +2687,8 @@ def debug(module, name, pm=False):
2653 2687
 ######################################################################
2654 2688
 ## 10. Example Usage
2655 2689
 ######################################################################
  2690
+
  2691
+
2656 2692
 class _TestClass:
2657 2693
     """
2658 2694
     A pointless class, for sanity-checking of docstring testing.
@@ -2747,6 +2783,7 @@ def get(self):
2747 2783
             """,
2748 2784
            }
2749 2785
 
  2786
+
2750 2787
 def _test():
2751 2788
     r = unittest.TextTestRunner()
2752 2789
     r.run(DocTestSuite())
3  django/test/testcases.py
@@ -61,9 +61,11 @@ def to_list(value):
61 61
 real_leave_transaction_management = transaction.leave_transaction_management
62 62
 real_abort = transaction.abort
63 63
 
  64
+
64 65
 def nop(*args, **kwargs):
65 66
     return
66 67
 
  68
+
67 69
 def disable_transaction_methods():
68 70
     transaction.commit = nop
69 71
     transaction.rollback = nop
@@ -71,6 +73,7 @@ def disable_transaction_methods():
71 73
     transaction.leave_transaction_management = nop
72 74
     transaction.abort = nop
73 75
 
  76
+
74 77
 def restore_transaction_methods():
75 78
     transaction.commit = real_commit
76 79
     transaction.rollback = real_rollback
1  django/utils/_os.py
@@ -53,6 +53,7 @@ def npath(path):
53 53
         return path.encode(fs_encoding)
54 54
     return path
55 55
 
  56
+
56 57
 def safe_join(base, *paths):
57 58
     """
58 59
     Joins one or more path components to the base path component intelligently.
8  django/utils/autoreload.py
@@ -119,6 +119,7 @@ def gen_filenames():
119 119
         if os.path.exists(filename):
120 120
             yield filename
121 121
 
  122
+
122 123
 def inotify_code_changed():
123 124
     """
124 125
     Checks for changed code using inotify. After being called
@@ -149,6 +150,7 @@ def update_watch(sender=None, **kwargs):
149 150
     # If we are here the code must have changed.
150 151
     return True
151 152
 
  153
+
152 154
 def kqueue_code_changed():
153 155
     """
154 156
     Checks for changed code using kqueue. After being called
@@ -193,6 +195,7 @@ def kqueue_code_changed():
193 195
 
194 196
     return True
195 197
 
  198
+
196 199
 def code_changed():
197 200
     global _mtimes, _win
198 201
     for filename in gen_filenames():
@@ -212,6 +215,7 @@ def code_changed():
212 215
             return True
213 216
     return False
214 217
 
  218
+
215 219
 def check_errors(fn):
216 220
     def wrapper(*args, **kwargs):
217 221
         try:
@@ -233,6 +237,7 @@ def wrapper(*args, **kwargs):
233 237
 
234 238
     return wrapper
235 239
 
  240
+
236 241
 def ensure_echo_on():
237 242
     if termios:
238 243
         fd = sys.stdin
@@ -248,6 +253,7 @@ def ensure_echo_on():
248 253
                 if old_handler is not None:
249 254
                     signal.signal(signal.SIGTTOU, old_handler)
250 255
 
  256
+
251 257
 def reloader_thread():
252 258
     ensure_echo_on()
253 259
     if USE_INOTIFY:
@@ -273,6 +279,7 @@ def restart_with_reloader():
273 279
         if exit_code != 3:
274 280
             return exit_code
275 281
 
  282
+
276 283
 def python_reloader(main_func, args, kwargs):
277 284
     if os.environ.get("RUN_MAIN") == "true":
278 285
         thread.start_new_thread(main_func, args, kwargs)
@@ -290,6 +297,7 @@ def python_reloader(main_func, args, kwargs):
290 297
         except KeyboardInterrupt:
291 298
             pass
292 299
 
  300
+
293 301
 def jython_reloader(main_func, args, kwargs):
294 302
     from _systemrestart import SystemRestart
295 303
     thread.start_new_thread(main_func, args)
12  django/utils/cache.py
@@ -31,6 +31,7 @@
31 31
 
32 32
 cc_delim_re = re.compile(r'\s*,\s*')
33 33
 
  34
+
34 35
 def patch_cache_control(response, **kwargs):
35 36
     """
36 37
     This function patches the Cache-Control header by adding all
@@ -79,6 +80,7 @@ def dictvalue(t):
79 80
     cc = ', '.join(dictvalue(el) for el in cc.items())
80 81
     response['Cache-Control'] = cc
81 82
 
  83
+
82 84
 def get_max_age(response):
83 85
     """
84 86
     Returns the max-age from the response Cache-Control header as an integer
@@ -94,11 +96,13 @@ def get_max_age(response):
94 96
         except (ValueError, TypeError):
95 97
             pass
96 98
 
  99
+
97 100
 def _set_response_etag(response):
98 101
     if not response.streaming:
99 102
         response['ETag'] = '"%s"' % hashlib.md5(response.content).hexdigest()
100 103
     return response
101 104
 
  105
+
102 106
 def patch_response_headers(response, cache_timeout=None):
103 107
     """
104 108
     Adds some useful headers to the given HttpResponse object:
@@ -124,12 +128,14 @@ def patch_response_headers(response, cache_timeout=None):
124 128
         response['Expires'] = http_date(time.time() + cache_timeout)
125 129
     patch_cache_control(response, max_age=cache_timeout)
126 130
 
  131
+
127 132
 def add_never_cache_headers(response):
128 133
     """
129 134
     Adds headers to a response to indicate that a page should never be cached.
130 135
     """
131 136
     patch_response_headers(response, cache_timeout=-1)
132 137
 
  138
+
133 139
 def patch_vary_headers(response, newheaders):
134 140
     """
135 141
     Adds (or updates) the "Vary" header in the given HttpResponse object.
@@ -149,6 +155,7 @@ def patch_vary_headers(response, newheaders):
149 155
                           if newheader.lower() not in existing_headers]
150 156
     response['Vary'] = ', '.join(vary_headers + additional_headers)
151 157
 
  158
+
152 159
 def has_vary_header(response, header_query):
153 160
     """
154 161
     Checks to see if the response has a given header name in its Vary header.
@@ -159,6 +166,7 @@ def has_vary_header(response, header_query):
159 166
     existing_headers = set(header.lower() for header in vary_headers)
160 167
     return header_query.lower() in existing_headers
161 168
 
  169
+
162 170
 def _i18n_cache_key_suffix(request, cache_key):
163 171
     """If necessary, adds the current locale or time zone to the cache key."""
164 172
     if settings.USE_I18N or settings.USE_L10N:
@@ -175,6 +183,7 @@ def _i18n_cache_key_suffix(request, cache_key):
175 183
         cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
176 184
     return cache_key
177 185
 
  186
+
178 187
 def _generate_cache_key(request, method, headerlist, key_prefix):
179 188
     """Returns a cache key from the headers given in the header list."""
180 189
     ctx = hashlib.md5()
@@ -187,6 +196,7 @@ def _generate_cache_key(request, method, headerlist, key_prefix):
187 196
         key_prefix, method, path.hexdigest(), ctx.hexdigest())
188 197
     return _i18n_cache_key_suffix(request, cache_key)
189 198
 
  199
+
190 200
 def _generate_cache_header_key(key_prefix, request):
191 201
     """Returns a cache key for the header cache."""
192 202
     path = hashlib.md5(force_bytes(iri_to_uri(request.get_full_path())))
@@ -194,6 +204,7 @@ def _generate_cache_header_key(key_prefix, request):
194 204
         key_prefix, path.hexdigest())
195 205
     return _i18n_cache_key_suffix(request, cache_key)
196 206
 
  207
+
197 208
 def get_cache_key(request, key_prefix=None, method='GET', cache=None):
198 209
     """
199 210
     Returns a cache key based on the request path and query. It can be used
@@ -215,6 +226,7 @@ def get_cache_key(request, key_prefix=None, method='GET', cache=None):
215 226
     else:
216 227
         return None
217 228
 
  229
+
218 230
 def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None):
219 231
     """
220 232
     Learns what headers to take into account for some request path from the
6  django/utils/datastructures.py
@@ -3,6 +3,7 @@
3 3
 from collections import OrderedDict
4 4
 from django.utils import six
5 5
 
  6
+
6 7
 class MergeDict(object):
7 8
     """
8 9
     A simple class for creating new "virtual" dictionaries that actually look
@@ -117,6 +118,7 @@ def __repr__(self):
117 118
         dictreprs = ', '.join(repr(d) for d in self.dicts)
118 119
         return '%s(%s)' % (self.__class__.__name__, dictreprs)
119 120
 
  121
+
120 122
 class SortedDict(dict):
121 123
     """
122 124
     A dictionary that keeps its keys in the order in which they're inserted.
@@ -239,6 +241,7 @@ def clear(self):
239 241
         super(SortedDict, self).clear()
240 242
         self.keyOrder = []
241 243
 
  244
+
242 245
 class OrderedSet(object):
243 246
     """
244 247
     A set which keeps the ordering of the inserted items.
@@ -269,9 +272,11 @@ def __contains__(self, item):
269 272
     def __nonzero__(self):
270 273
         return bool(self.dict)
271 274
 
  275
+
272 276
 class MultiValueDictKeyError(KeyError):
273 277
     pass
274 278
 
  279
+
275 280
 class MultiValueDict(dict):
276 281
     """
277 282
     A subclass of dictionary customized to handle multiple values for the
@@ -504,6 +509,7 @@ def complain(self, *wargs, **kwargs):
504 509
     sort = complain
505 510
     reverse = complain
506 511
 
  512
+
507 513
 class DictWrapper(dict):
508 514
     """
509 515
     Wraps accesses to a dictionary so that certain values (those starting with
2  django/utils/dateformat.py
@@ -26,6 +26,7 @@
26 26
 re_formatchars = re.compile(r'(?<!\\)([aAbBcdDeEfFgGhHiIjlLmMnNoOPrsStTUuwWyYzZ])')
27 27
 re_escaped = re.compile(r'\\(.)')
28 28
 
  29
+
29 30
 class Formatter(object):
30 31
     def format(self, formatstr):
31 32
         pieces = []
@@ -36,6 +37,7 @@ def format(self, formatstr):
36 37
                 pieces.append(re_escaped.sub(r'\1', piece))
37 38
         return ''.join(pieces)
38 39
 
  40
+
39 41
 class TimeFormat(Formatter):
40 42
 
41 43
     def __init__(self, obj):
2  django/utils/dateparse.py
@@ -39,6 +39,7 @@ def parse_date(value):
39 39
         kw = dict((k, int(v)) for k, v in six.iteritems(match.groupdict()))
40 40
         return datetime.date(**kw)
41 41
 
  42
+
42 43
 def parse_time(value):
43 44
     """Parses a string and return a datetime.time.
44 45
 
@@ -56,6 +57,7 @@ def parse_time(value):
56 57
         kw = dict((k, int(v)) for k, v in six.iteritems(kw) if v is not None)
57 58
         return datetime.time(**kw)
58 59
 
  60
+
59 61
 def parse_datetime(value):
60 62
     """Parses a string and return a datetime.datetime.
61 63
 
4  django/utils/datetime_safe.py
@@ -30,10 +30,12 @@ def combine(cls, date, time):
30 30
     def date(self):
31 31
         return date(self.year, self.month, self.day)
32 32
 
  33
+
33 34
 def new_date(d):
34 35
     "Generate a safe date from a datetime.date object."
35 36
     return date(d.year, d.month, d.day)
36 37
 
  38
+
37 39
 def new_datetime(d):
38 40
     """
39 41
     Generate a safe datetime from a datetime.date or datetime.datetime object.
@@ -47,6 +49,7 @@ def new_datetime(d):
47 49
 # Allowed if there's an even number of "%"s because they are escaped.
48 50
 _illegal_formatting = re.compile(r"((^|[^%])(%%)*%[sy])")
49 51
 
  52
+
50 53
 def _findall(text, substr):
51 54
     # Also finds overlaps
52 55
     sites = []
@@ -59,6 +62,7 @@ def _findall(text, substr):
59 62
         i = j + 1
60 63
     return sites
61 64
 
  65
+
62 66
 def strftime(dt, fmt):
63 67
     if dt.year >= 1900:
64 68
         return super(type(dt), dt).strftime(fmt)
7  django/utils/dictconfig.py
@@ -32,6 +32,7 @@
32 32
 
33 33
 IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)
34 34
 
  35
+
35 36
 def valid_ident(s):
36 37
     m = IDENTIFIER.match(s)
37 38
     if not m:
@@ -65,6 +66,7 @@ def _checkLevel(level):
65 66
 # Each wrapper should have a configurator attribute holding the actual
66 67
 # configurator to use for conversion.
67 68
 
  69
+
68 70
 class ConvertingDict(dict):
69 71
     """A converting dictionary wrapper."""
70 72
 
@@ -102,6 +104,7 @@ def pop(self, key, default=None):
102 104
                 result.key = key
103 105
         return result
104 106
 
  107
+
105 108
 class ConvertingList(list):
106 109
     """A converting list wrapper."""
107 110
     def __getitem__(self, key):
@@ -125,6 +128,7 @@ def pop(self, idx=-1):
125 128
                 result.parent = self
126 129
         return result
127 130
 
  131
+
128 132
 class ConvertingTuple(tuple):
129 133
     """A converting tuple wrapper."""
130 134
     def __getitem__(self, key):
@@ -137,6 +141,7 @@ def __getitem__(self, key):
137 141
                 result.key = key
138 142
         return result
139 143
 
  144
+
140 145
 class BaseConfigurator(object):
141 146
     """
142 147
     The configurator base class which defines some useful defaults.
@@ -270,6 +275,7 @@ def as_tuple(self, value):
270 275
             value = tuple(value)
271 276
         return value
272 277
 
  278
+
273 279
 class DictConfigurator(BaseConfigurator):
274 280
     """
275 281
     Configure logging using a dictionary-like object to describe the
@@ -555,6 +561,7 @@ def configure_root(self, config, incremental=False):
555 561
 
556 562
 dictConfigClass = DictConfigurator
557 563
 
  564
+
558 565
 def dictConfig(config):
559 566
     """Configure logging using a dictionary."""
560 567
     dictConfigClass(config).configure()
7  django/utils/encoding.py
@@ -38,6 +38,7 @@ def python_2_unicode_compatible(klass):
38 38
         klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
39 39
     return klass
40 40
 
  41
+
41 42
 def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'):
42 43
     """
43 44
     Returns a text object representing 's' -- unicode on Python 2 and str on
@@ -50,6 +51,7 @@ def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'):
50 51
         return s
51 52
     return force_text(s, encoding, strings_only, errors)
52 53
 
  54
+
53 55
 def is_protected_type(obj):
54 56
     """Determine if the object instance is of a protected type.
55 57
 
@@ -59,6 +61,7 @@ def is_protected_type(obj):
59 61
     return isinstance(obj, six.integer_types + (type(None), float, Decimal,
60 62
         datetime.datetime, datetime.date, datetime.time))
61 63
 
  64
+
62 65
 def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
63 66
     """
64 67
     Similar to smart_text, except that lazy instances are resolved to
@@ -100,6 +103,7 @@ def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
100 103
                     errors) for arg in s])
101 104
     return s
102 105
 
  106
+
103 107
 def smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
104 108
     """
105 109
     Returns a bytestring version of 's', encoded as specified in 'encoding'.
@@ -168,6 +172,7 @@ def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
168 172
 Apply force_text in Python 3 and force_bytes in Python 2.
169 173
 """
170 174
 
  175
+
171 176
 def iri_to_uri(iri):
172 177
     """
173 178
     Convert an Internationalized Resource Identifier (IRI) portion to a URI
@@ -195,6 +200,7 @@ def iri_to_uri(iri):
195 200
         return iri
196 201
     return quote(force_bytes(iri), safe=b"/#%[]=:;$&()+,!?*@'~")
197 202
 
  203
+
198 204
 def filepath_to_uri(path):
199 205
     """Convert a file system path to a URI portion that is suitable for
200 206
     inclusion in a URL.
@@ -214,6 +220,7 @@ def filepath_to_uri(path):
214 220
     # some flexibility for hardcoding separators.
215 221
     return quote(force_bytes(path).replace(b"\\", b"/"), safe=b"/~!*()'")
216 222
 
  223
+
217 224
 def get_system_encoding():
218 225
     """
219 226
     The encoding of the default system locale but falls back to the given
8  django/utils/feedgenerator.py
@@ -54,6 +54,7 @@ def rfc2822_date(date):
54 54
     else:
55 55
         return time_str + '-0000'
56 56
 
  57
+
57 58
 def rfc3339_date(date):
58 59
     # Support datetime objects older than 1900
59 60
     date = datetime_safe.new_datetime(date)
@@ -68,6 +69,7 @@ def rfc3339_date(date):
68 69
     else:
69 70
         return time_str + 'Z'
70 71
 
  72
+
71 73
 def get_tag_uri(url, date):
72 74
     """
73 75
     Creates a TagURI.
@@ -80,6 +82,7 @@ def get_tag_uri(url, date):
80 82
         d = ',%s' % datetime_safe.new_datetime(date).strftime('%Y-%m-%d')
81 83
     return 'tag:%s%s:%s/%s' % (bits.hostname, d, bits.path, bits.fragment)
82 84
 
  85
+
83 86
 class SyndicationFeed(object):
84 87
     "Base class for all syndication feeds. Subclasses should provide write()"
85 88
     def __init__(self, title, link, description, language=None, author_email=None,
@@ -205,6 +208,7 @@ def latest_post_date(self):
205 208
 
206 209
         return latest_date or datetime.datetime.now()
207 210
 
  211
+
208 212
 class Enclosure(object):
209 213
     "Represents an RSS enclosure"
210 214
     def __init__(self, url, length, mime_type):
@@ -212,6 +216,7 @@ def __init__(self, url, length, mime_type):
212 216
         self.length, self.mime_type = length, mime_type
213 217
         self.url = iri_to_uri(url)
214 218
 
  219
+
215 220
 class RssFeed(SyndicationFeed):
216 221
     mime_type = 'application/rss+xml; charset=utf-8'
217 222
 
@@ -255,6 +260,7 @@ def add_root_elements(self, handler):
255 260
     def endChannelElement(self, handler):
256 261
         handler.endElement("channel")
257 262
 
  263
+
258 264
 class RssUserland091Feed(RssFeed):
259 265
     _version = "0.91"
260 266
 
@@ -264,6 +270,7 @@ def add_item_elements(self, handler, item):
264 270
         if item['description'] is not None:
265 271
             handler.addQuickElement("description", item['description'])
266 272
 
  273
+
267 274
 class Rss201rev2Feed(RssFeed):
268 275
     # Spec: http://blogs.law.harvard.edu/tech/rss
269 276
     _version = "2.0"
@@ -306,6 +313,7 @@ def add_item_elements(self, handler, item):
306 313
         for cat in item['categories']:
307 314
             handler.addQuickElement("category", cat)
308 315
 
  316
+
309 317
 class Atom1Feed(SyndicationFeed):
310 318
     # Spec: http://atompub.org/2005/07/11/draft-ietf-atompub-format-10.html
311 319
     mime_type = 'application/atom+xml; charset=utf-8'
10  django/utils/formats.py
@@ -30,6 +30,7 @@
30 30
     ),
31 31
 }
32 32
 
  33
+
33 34
 def reset_format_cache():
34 35
     """Clear any cached formats.
35 36
 
@@ -40,6 +41,7 @@ def reset_format_cache():
40 41
     _format_cache = {}
41 42
     _format_modules_cache = {}
42 43
 
  44
+
43 45
 def iter_format_modules(lang, format_module_path=None):
44 46
     """
45 47
     Does the heavy lifting of finding format modules.
@@ -60,6 +62,7 @@ def iter_format_modules(lang, format_module_path=None):
60 62
                 except ImportError:
61 63
                     pass
62 64
 
  65
+
63 66
 def get_format_modules(lang=None, reverse=False):
64 67
     """
65 68
     Returns a list of the format modules found
@@ -71,6 +74,7 @@ def get_format_modules(lang=None, reverse=False):
71 74
         return list(reversed(modules))
72 75
     return modules
73 76
 
  77
+
74 78
 def get_format(format_type, lang=None, use_l10n=None):
75 79
     """
76 80
     For a specific format type, returns the format for the current
@@ -110,6 +114,7 @@ def get_format(format_type, lang=None, use_l10n=None):
110 114
 
111 115
 get_format_lazy = lazy(get_format, six.text_type, list, tuple)
112 116
 
  117
+
113 118
 def date_format(value, format=None, use_l10n=None):
114 119
     """
115 120
     Formats a datetime.date or datetime.datetime object using a
@@ -120,6 +125,7 @@ def date_format(value, format=None, use_l10n=None):
120 125
     """
121 126
     return dateformat.format(value, get_format(format or 'DATE_FORMAT', use_l10n=use_l10n))
122 127
 
  128
+
123 129
 def time_format(value, format=None, use_l10n=None):
124 130
     """
125 131
     Formats a datetime.time object using a localizable format
@@ -129,6 +135,7 @@ def time_format(value, format=None, use_l10n=None):
129 135
     """
130 136
     return dateformat.time_format(value, get_format(format or 'TIME_FORMAT', use_l10n=use_l10n))
131 137
 
  138
+
132 139
 def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False):
133 140
     """
134 141
     Formats a numeric value using localization settings
@@ -149,6 +156,7 @@ def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False):
149 156
         force_grouping=force_grouping
150 157
     )
151 158
 
  159
+
152 160
 def localize(value, use_l10n=None):
153 161
     """
154 162
     Checks if value is a localizable type (date, number...) and returns it
@@ -170,6 +178,7 @@ def localize(value, use_l10n=None):
170 178
     else:
171 179
         return value
172 180
 
  181
+
173 182
 def localize_input(value, default=None):
174 183
     """
175 184
     Checks if an input value is a localizable type and returns it
@@ -190,6 +199,7 @@ def localize_input(value, default=None):
190 199
         return value.strftime(format)
191 200
     return value
192 201
 
  202
+
193 203
 def sanitize_separators(value):
194 204
     """
195 205
     Sanitizes a value according to the current decimal and
11  django/utils/html.py
@@ -72,6 +72,7 @@ def conditional_escape(text):
72 72
     else:
73 73
         return escape(text)
74 74
 
  75
+
75 76
 def format_html(format_string, *args, **kwargs):
76 77
     """
77 78
     Similar to str.format, but passes all arguments through conditional_escape,
@@ -83,6 +84,7 @@ def format_html(format_string, *args, **kwargs):
83 84
                         six.iteritems(kwargs))
84 85
     return mark_safe(format_string.format(*args_safe, **kwargs_safe))
85 86
 
  87
+
86 88
 def format_html_join(sep, format_string, args_generator):
87 89
     """
88 90
     A wrapper of format_html, for the common case of a group of arguments that
@@ -133,6 +135,7 @@ def handle_charref(self, name):
133 135
     def get_data(self):
134 136
         return ''.join(self.fed)
135 137
 
  138
+
136 139
 def strip_tags(value):
137 140
     """Returns the given HTML with all tags stripped."""
138 141
     s = MLStripper()
@@ -145,6 +148,7 @@ def strip_tags(value):
145 148
         return s.get_data()
146 149
 strip_tags = allow_lazy(strip_tags)
147 150
 
  151
+
148 152
 def remove_tags(html, tags):
149 153
     """Returns the given HTML with given tags removed."""
150 154
     tags = [re.escape(tag) for tag in tags.split()]
@@ -156,21 +160,25 @@ def remove_tags(html, tags):
156 160
     return html
157 161
 remove_tags = allow_lazy(remove_tags, six.text_type)
158 162
 
  163
+
159 164
 def strip_spaces_between_tags(value):
160 165
     """Returns the given HTML with spaces between tags removed."""
161 166
     return re.sub(r'>\s+<', '><', force_text(value))
162 167
 strip_spaces_between_tags = allow_lazy(strip_spaces_between_tags, six.text_type)
163 168
 
  169
+
164 170
 def strip_entities(value):
165 171
     """Returns the given HTML with all entities (&something;) stripped."""
166 172
     return re.sub(r'&(?:\w+|#\d+);', '', force_text(value))
167 173
 strip_entities = allow_lazy(strip_entities, six.text_type)
168 174
 
  175
+
169 176
 def fix_ampersands(value):
170 177
     """Returns the given HTML with all unencoded ampersands encoded correctly."""
171 178
     return unencoded_ampersands_re.sub('&amp;', force_text(value))
172 179
 fix_ampersands = allow_lazy(fix_ampersands, six.text_type)
173 180
 
  181
+
174 182
 def smart_urlquote(url):
175 183
     "Quotes a URL if it isn't already quoted."
176 184
     # Handle IDN before quoting.
@@ -192,6 +200,7 @@ def smart_urlquote(url):
192 200
 
193 201
     return force_text(url)
194 202
 
  203
+
195 204
 def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
196 205
     """
197 206
     Converts any URLs in text into clickable links.
@@ -269,6 +278,7 @@ def trim_url(x, limit=trim_url_limit):
269 278
     return ''.join(words)
270 279
 urlize = allow_lazy(urlize, six.text_type)
271 280
 
  281
+
272 282
 def clean_html(text):
273 283
     """
274 284
     Clean the given HTML.  Specifically, do the following:
@@ -304,6 +314,7 @@ def replace_p_tags(match):
304 314
     return text
305 315
 clean_html = allow_lazy(clean_html, six.text_type)
306 316
 
  317
+
307 318
 def avoid_wrapping(value):
308 319
     """
309 320
     Avoid text wrapping in the middle of a phrase by adding non-breaking
17  django/utils/http.py
@@ -30,6 +30,7 @@
30 30
 RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T))
31 31
 ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y))
32 32
 
  33
+
33 34
 def urlquote(url, safe='/'):
34 35
     """
35 36
     A version of Python's urllib.quote() function that can operate on unicode
@@ -40,6 +41,7 @@ def urlquote(url, safe='/'):
40 41
     return force_text(quote(force_str(url), force_str(safe)))
41 42
 urlquote = allow_lazy(urlquote, six.text_type)
42 43
 
  44
+
43 45
 def urlquote_plus(url, safe=''):
44 46
     """
45 47
     A version of Python's urllib.quote_plus() function that can operate on
@@ -50,6 +52,7 @@ def urlquote_plus(url, safe=''):
50 52
     return force_text(quote_plus(force_str(url), force_str(safe)))
51 53
 urlquote_plus = allow_lazy(urlquote_plus, six.text_type)
52 54
 
  55
+
53 56
 def urlunquote(quoted_url):
54 57
     """
55 58
     A wrapper for Python's urllib.unquote() function that can operate on
@@ -58,6 +61,7 @@ def urlunquote(quoted_url):
58 61
     return force_text(unquote(force_str(quoted_url)))
59 62
 urlunquote = allow_lazy(urlunquote, six.text_type)
60 63
 
  64
+
61 65
 def urlunquote_plus(quoted_url):
62 66
     """
63 67
     A wrapper for Python's urllib.unquote_plus() function that can operate on
@@ -66,6 +70,7 @@ def urlunquote_plus(quoted_url):
66 70
     return force_text(unquote_plus(force_str(quoted_url)))
67 71
 urlunquote_plus = allow_lazy(urlunquote_plus, six.text_type)
68 72
 
  73
+
69 74
 def urlencode(query, doseq=0):
70 75
     """
71 76
     A version of Python's urllib.urlencode() function that can operate on
@@ -82,6 +87,7 @@ def urlencode(query, doseq=0):
82 87
             for k, v in query],
83 88
         doseq)
84 89
 
  90
+
85 91
 def cookie_date(epoch_seconds=None):
86 92
     """
87 93
     Formats the time to ensure compatibility with Netscape's cookie standard.
@@ -95,6 +101,7 @@ def cookie_date(epoch_seconds=None):
95 101
     rfcdate = formatdate(epoch_seconds)
96 102
     return '%s-%s-%s GMT' % (rfcdate[:7], rfcdate[8:11], rfcdate[12:25])
97 103
 
  104
+
98 105
 def http_date(epoch_seconds=None):
99 106
     """
100 107
     Formats the time to match the RFC1123 date format as specified by HTTP
@@ -108,6 +115,7 @@ def http_date(epoch_seconds=None):
108 115
     """
109 116
     return formatdate(epoch_seconds, usegmt=True)
110 117
 
  118
+
111 119
 def parse_http_date(date):
112 120
     """
113 121
     Parses a date format as specified by HTTP RFC2616 section 3.3.1.
@@ -143,6 +151,7 @@ def parse_http_date(date):
143 151
     except Exception:
144 152
         six.reraise(ValueError, ValueError("%r is not a valid date" % date), sys.exc_info()[2])
145 153
 
  154
+
146 155
 def parse_http_date_safe(date):
147 156
     """
148 157
     Same as parse_http_date, but returns None if the input is invalid.
@@ -152,6 +161,7 @@ def parse_http_date_safe(date):
152 161
     except Exception:
153 162
         pass
154 163
 
  164
+
155 165
 # Base 36 functions: useful for generating compact URLs
156 166
 
157 167
 def base36_to_int(s):
@@ -171,6 +181,7 @@ def base36_to_int(s):
171 181
         raise ValueError("Base36 input too large")
172 182
     return value
173 183
 
  184
+
174 185
 def int_to_base36(i):
175 186
     """
176 187
     Converts an integer to a base36 string
@@ -199,6 +210,7 @@ def int_to_base36(i):
199 210
         factor -= 1
200 211
     return ''.join(base36)
201 212
 
  213
+
202 214
 def urlsafe_base64_encode(s):
203 215
     """
204 216
     Encodes a bytestring in base64 for use in URLs, stripping any trailing
@@ -206,6 +218,7 @@ def urlsafe_base64_encode(s):
206 218
     """
207 219
     return base64.urlsafe_b64encode(s).rstrip(b'\n=')
208 220
 
  221
+
209 222
 def urlsafe_base64_decode(s):
210 223
     """
211 224
     Decodes a base64 encoded string, adding back any trailing equal signs that
@@ -217,6 +230,7 @@ def urlsafe_base64_decode(s):
217 230
     except (LookupError, BinasciiError) as e:
218 231
         raise ValueError(e)
219 232
 
  233
+
220 234
 def parse_etags(etag_str):
221 235
     """
222 236
     Parses a string with one or several etags passed in If-None-Match and
@@ -230,12 +244,14 @@ def parse_etags(etag_str):
230 244
     etags = [e.encode('ascii').decode('unicode_escape') for e in etags]
231 245
     return etags
232 246
 
  247
+
233 248
 def quote_etag(etag):
234 249
     """
235 250
     Wraps a string in double quotes escaping contents as necessary.
236 251
     """
237 252
     return '"%s"' % etag.replace('\\', '\\\\').replace('"', '\\"')
238 253
 
  254
+
239 255
 def same_origin(url1, url2):
240 256
     """
241 257
     Checks if two URLs are 'same-origin'
@@ -246,6 +262,7 @@ def same_origin(url1, url2):
246 262
     except ValueError:
247 263
         return False
248 264
 
  265
+
249 266
 def is_safe_url(url, host=None):
250 267
     """
251 268
     Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
5  django/utils/regex_helper.py
@@ -202,6 +202,7 @@ def normalize(pattern):
202 202
 
203 203
     return list(zip(*flatten_result(result)))
204 204
 
  205
+
205 206
 def next_char(input_iter):
206 207
     """
207 208
     An iterator that yields the next character from "pattern_iter", respecting
@@ -222,6 +223,7 @@ def next_char(input_iter):
222 223
             continue
223 224
         yield representative, True
224 225
 
  226
+
225 227
 def walk_to_end(ch, input_iter):
226 228
     """
227 229
     The iterator is currently inside a capturing group. We want to walk to the
@@ -242,6 +244,7 @@ def walk_to_end(ch, input_iter):
242 244
                 return
243 245
             nesting -= 1
244 246
 
  247
+
245 248
 def get_quantifier(ch, input_iter):
246 249
     """
247 250
     Parse a quantifier from the input, where "ch" is the first character in the
@@ -278,6 +281,7 @@ def get_quantifier(ch, input_iter):
278 281
         ch = None
279 282
     return int(values[0]), ch
280 283
 
  284
+
281 285
 def contains(source, inst):
282 286
     """
283 287
     Returns True if the "source" contains an instance of "inst". False,
@@ -291,6 +295,7 @@ def contains(source, inst):
291 295
                 return True
292 296
     return False
293 297
 
  298
+
294 299
 def flatten_result(source):
295 300
     """
296 301
     Turns the given source sequence into a list of reg-exp possibilities and
5  django/utils/safestring.py
@@ -32,6 +32,7 @@ class EscapeText(six.text_type, EscapeData):
32 32
     # backwards compatibility for Python 2
33 33
     EscapeUnicode = EscapeText
34 34
 
  35
+
35 36
 class SafeData(object):
36 37
     def __html__(self):
37 38
         """
@@ -41,6 +42,7 @@ def __html__(self):
41 42
         """
42 43
         return self
43 44
 
  45
+
44 46
 class SafeBytes(bytes, SafeData):
45 47
     """
46 48
     A bytes subclass that has been specifically marked as "safe" (requires no
@@ -75,6 +77,7 @@ def _proxy_method(self, *args, **kwargs):
75 77
 
76 78
     decode = curry(_proxy_method, method=bytes.decode)
77 79
 
  80
+
78 81
 class SafeText(six.text_type, SafeData):
79 82
     """