Refs #27656 -- Updated django.template/tag docstring verbs according to PEP 257.

This commit is contained in:
Anton Samarchyan 2017-01-24 15:36:36 -05:00 committed by Tim Graham
parent b935190572
commit 4696078832
17 changed files with 193 additions and 239 deletions

View File

@ -13,9 +13,9 @@ class BaseEngine:
def __init__(self, params): def __init__(self, params):
""" """
Initializes the template engine. Initialize the template engine.
Receives the configuration settings as a dict. `params` is a dict of configuration settings.
""" """
params = params.copy() params = params.copy()
self.name = params.pop('NAME') self.name = params.pop('NAME')
@ -33,7 +33,7 @@ class BaseEngine:
def from_string(self, template_code): def from_string(self, template_code):
""" """
Creates and returns a template for the given source code. Create and return a template for the given source code.
This method is optional. This method is optional.
""" """
@ -43,9 +43,9 @@ class BaseEngine:
def get_template(self, template_name): def get_template(self, template_name):
""" """
Loads and returns a template for the given name. Load and return a template for the given name.
Raises TemplateDoesNotExist if no such template exists. Raise TemplateDoesNotExist if no such template exists.
""" """
raise NotImplementedError( raise NotImplementedError(
"subclasses of BaseEngine must provide " "subclasses of BaseEngine must provide "
@ -57,7 +57,7 @@ class BaseEngine:
@cached_property @cached_property
def template_dirs(self): def template_dirs(self):
""" """
Returns a list of directories to search for templates. Return a list of directories to search for templates.
""" """
# Immutable return value because it's cached and shared by callers. # Immutable return value because it's cached and shared by callers.
template_dirs = tuple(self.dirs) template_dirs = tuple(self.dirs)
@ -67,9 +67,9 @@ class BaseEngine:
def iter_template_filenames(self, template_name): def iter_template_filenames(self, template_name):
""" """
Iterates over candidate files for template_name. Iterate over candidate files for template_name.
Ignores files that don't lie inside configured template dirs to avoid Ignore files that don't lie inside configured template dirs to avoid
directory traversal attacks. directory traversal attacks.
""" """
for template_dir in self.template_dirs: for template_dir in self.template_dirs:

View File

@ -83,7 +83,7 @@ class Origin:
def get_exception_info(exception): def get_exception_info(exception):
""" """
Formats exception information for display on the debug page using the Format exception information for display on the debug page using the
structure described in the template API documentation. structure described in the template API documentation.
""" """
context_lines = 10 context_lines = 10

View File

@ -391,7 +391,7 @@ class DebugLexer(Lexer):
""" """
Split a template string into tokens and annotates each token with its Split a template string into tokens and annotates each token with its
start and end position in the source. This is slower than the default start and end position in the source. This is slower than the default
lexer so we only use it when debug is True. lexer so only use it when debug is True.
""" """
lineno = 1 lineno = 1
result = [] result = []
@ -616,7 +616,7 @@ filter_re = re.compile(filter_raw_string, re.VERBOSE)
class FilterExpression: class FilterExpression:
""" """
Parses a variable token and its optional filters (all as a single string), Parse a variable token and its optional filters (all as a single string),
and return a list of tuples of the filter name and arguments. and return a list of tuples of the filter name and arguments.
Sample:: Sample::
@ -823,7 +823,7 @@ class Variable:
def _resolve_lookup(self, context): def _resolve_lookup(self, context):
""" """
Performs resolution of a real variable (i.e. not a literal) against the Perform resolution of a real variable (i.e. not a literal) against the
given context. given context.
As indicated by the method's name, this method is an implementation As indicated by the method's name, this method is an implementation
@ -969,7 +969,7 @@ class TextNode(Node):
def render_value_in_context(value, context): def render_value_in_context(value, context):
""" """
Converts any value to a string to become part of a rendered template. This Convert any value to a string to become part of a rendered template. This
means escaping, if required, and conversion to a string. If value is a means escaping, if required, and conversion to a string. If value is a
string, it's expected to already be translated. string, it's expected to already be translated.
""" """
@ -1007,22 +1007,19 @@ kwarg_re = re.compile(r"(?:(\w+)=)?(.+)")
def token_kwargs(bits, parser, support_legacy=False): def token_kwargs(bits, parser, support_legacy=False):
""" """
A utility method for parsing token keyword arguments. Parse token keyword arguments and return a dictionary of the arguments
retrieved from the ``bits`` token list.
:param bits: A list containing remainder of the token (split by spaces) `bits` is a list containing the remainder of the token (split by spaces)
that is to be checked for arguments. Valid arguments will be removed that is to be checked for arguments. Valid arguments are removed from this
from this list. list.
:param support_legacy: If set to true ``True``, the legacy format `support_legacy` - if True, the legacy format ``1 as foo`` is accepted.
``1 as foo`` will be accepted. Otherwise, only the standard ``foo=1`` Otherwise, only the standard ``foo=1`` format is allowed.
format is allowed.
:returns: A dictionary of the arguments retrieved from the ``bits`` token
list.
There is no requirement for all remaining token ``bits`` to be keyword There is no requirement for all remaining token ``bits`` to be keyword
arguments, so the dictionary will be returned as soon as an invalid arguments, so return the dictionary as soon as an invalid argument format
argument format is reached. is reached.
""" """
if not bits: if not bits:
return {} return {}

View File

@ -108,7 +108,7 @@ class BaseContext:
def new(self, values=None): def new(self, values=None):
""" """
Returns a new context with the same properties, but with only the Return a new context with the same properties, but with only the
values given in 'values' stored. values given in 'values' stored.
""" """
new_context = copy(self) new_context = copy(self)
@ -117,7 +117,7 @@ class BaseContext:
def flatten(self): def flatten(self):
""" """
Returns self.dicts as one dictionary Return self.dicts as one dictionary.
""" """
flat = {} flat = {}
for d in self.dicts: for d in self.dicts:
@ -126,7 +126,7 @@ class BaseContext:
def __eq__(self, other): def __eq__(self, other):
""" """
Compares two contexts by comparing theirs 'dicts' attributes. Compare two contexts by comparing theirs 'dicts' attributes.
""" """
if isinstance(other, BaseContext): if isinstance(other, BaseContext):
# because dictionaries can be put in different order # because dictionaries can be put in different order
@ -166,7 +166,7 @@ class Context(BaseContext):
return duplicate return duplicate
def update(self, other_dict): def update(self, other_dict):
"Pushes other_dict to the stack of dictionaries in the Context" "Push other_dict to the stack of dictionaries in the Context"
if not hasattr(other_dict, '__getitem__'): if not hasattr(other_dict, '__getitem__'):
raise TypeError('other_dict must be a mapping (dictionary-like) object.') raise TypeError('other_dict must be a mapping (dictionary-like) object.')
if isinstance(other_dict, BaseContext): if isinstance(other_dict, BaseContext):

View File

@ -34,7 +34,7 @@ def csrf(request):
def debug(request): def debug(request):
""" """
Returns context variables helpful for debugging. Return context variables helpful for debugging.
""" """
context_extras = {} context_extras = {}
if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS: if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
@ -65,14 +65,14 @@ def tz(request):
def static(request): def static(request):
""" """
Adds static-related context variables to the context. Add static-related context variables to the context.
""" """
return {'STATIC_URL': settings.STATIC_URL} return {'STATIC_URL': settings.STATIC_URL}
def media(request): def media(request):
""" """
Adds media-related context variables to the context. Add media-related context variables to the context.
""" """
return {'MEDIA_URL': settings.MEDIA_URL} return {'MEDIA_URL': settings.MEDIA_URL}

View File

@ -61,7 +61,7 @@ def stringfilter(func):
@stringfilter @stringfilter
def addslashes(value): def addslashes(value):
""" """
Adds slashes before quotes. Useful for escaping strings in CSV, for Add slashes before quotes. Useful for escaping strings in CSV, for
example. Less useful for escaping JavaScript; use the ``escapejs`` example. Less useful for escaping JavaScript; use the ``escapejs``
filter instead. filter instead.
""" """
@ -71,24 +71,24 @@ def addslashes(value):
@register.filter(is_safe=True) @register.filter(is_safe=True)
@stringfilter @stringfilter
def capfirst(value): def capfirst(value):
"""Capitalizes the first character of the value.""" """Capitalize the first character of the value."""
return value and value[0].upper() + value[1:] return value and value[0].upper() + value[1:]
@register.filter("escapejs") @register.filter("escapejs")
@stringfilter @stringfilter
def escapejs_filter(value): def escapejs_filter(value):
"""Hex encodes characters for use in JavaScript strings.""" """Hex encode characters for use in JavaScript strings."""
return escapejs(value) return escapejs(value)
@register.filter(is_safe=True) @register.filter(is_safe=True)
def floatformat(text, arg=-1): def floatformat(text, arg=-1):
""" """
Displays a float to a specified number of decimal places. Display a float to a specified number of decimal places.
If called without an argument, it displays the floating point number with If called without an argument, display the floating point number with one
one decimal place -- but only if there's a decimal place to be displayed: decimal place -- but only if there's a decimal place to be displayed:
* num1 = 34.23234 * num1 = 34.23234
* num2 = 34.00000 * num2 = 34.00000
@ -97,24 +97,22 @@ def floatformat(text, arg=-1):
* {{ num2|floatformat }} displays "34" * {{ num2|floatformat }} displays "34"
* {{ num3|floatformat }} displays "34.3" * {{ num3|floatformat }} displays "34.3"
If arg is positive, it will always display exactly arg number of decimal If arg is positive, always display exactly arg number of decimal places:
places:
* {{ num1|floatformat:3 }} displays "34.232" * {{ num1|floatformat:3 }} displays "34.232"
* {{ num2|floatformat:3 }} displays "34.000" * {{ num2|floatformat:3 }} displays "34.000"
* {{ num3|floatformat:3 }} displays "34.260" * {{ num3|floatformat:3 }} displays "34.260"
If arg is negative, it will display arg number of decimal places -- but If arg is negative, display arg number of decimal places -- but only if
only if there are places to be displayed: there are places to be displayed:
* {{ num1|floatformat:"-3" }} displays "34.232" * {{ num1|floatformat:"-3" }} displays "34.232"
* {{ num2|floatformat:"-3" }} displays "34" * {{ num2|floatformat:"-3" }} displays "34"
* {{ num3|floatformat:"-3" }} displays "34.260" * {{ num3|floatformat:"-3" }} displays "34.260"
If the input float is infinity or NaN, the (platform-dependent) string If the input float is infinity or NaN, display the string representation
representation of that value will be displayed. of that value.
""" """
try: try:
input_val = repr(text) input_val = repr(text)
d = Decimal(input_val) d = Decimal(input_val)
@ -162,14 +160,14 @@ def floatformat(text, arg=-1):
@register.filter(is_safe=True) @register.filter(is_safe=True)
@stringfilter @stringfilter
def iriencode(value): def iriencode(value):
"""Escapes an IRI value for use in a URL.""" """Escape an IRI value for use in a URL."""
return iri_to_uri(value) return iri_to_uri(value)
@register.filter(is_safe=True, needs_autoescape=True) @register.filter(is_safe=True, needs_autoescape=True)
@stringfilter @stringfilter
def linenumbers(value, autoescape=True): def linenumbers(value, autoescape=True):
"""Displays text with line numbers.""" """Display text with line numbers."""
lines = value.split('\n') lines = value.split('\n')
# Find the maximum width of the line count, for use with zero padding # Find the maximum width of the line count, for use with zero padding
# string format command # string format command
@ -186,7 +184,7 @@ def linenumbers(value, autoescape=True):
@register.filter(is_safe=True) @register.filter(is_safe=True)
@stringfilter @stringfilter
def lower(value): def lower(value):
"""Converts a string into all lowercase.""" """Convert a string into all lowercase."""
return value.lower() return value.lower()
@ -194,7 +192,7 @@ def lower(value):
@stringfilter @stringfilter
def make_list(value): def make_list(value):
""" """
Returns the value turned into a list. Return the value turned into a list.
For an integer, it's a list of digits. For an integer, it's a list of digits.
For a string, it's a list of characters. For a string, it's a list of characters.
@ -206,9 +204,9 @@ def make_list(value):
@stringfilter @stringfilter
def slugify(value): def slugify(value):
""" """
Converts to ASCII. Converts spaces to hyphens. Removes characters that Convert to ASCII. Convert spaces to hyphens. Remove characters that aren't
aren't alphanumerics, underscores, or hyphens. Converts to lowercase. alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip
Also strips leading and trailing whitespace. leading and trailing whitespace.
""" """
return _slugify(value) return _slugify(value)
@ -216,7 +214,7 @@ def slugify(value):
@register.filter(is_safe=True) @register.filter(is_safe=True)
def stringformat(value, arg): def stringformat(value, arg):
""" """
Formats the variable according to the arg, a string formatting specifier. Format the variable according to the arg, a string formatting specifier.
This specifier uses Python string formating syntax, with the exception that This specifier uses Python string formating syntax, with the exception that
the leading "%" is dropped. the leading "%" is dropped.
@ -233,7 +231,7 @@ def stringformat(value, arg):
@register.filter(is_safe=True) @register.filter(is_safe=True)
@stringfilter @stringfilter
def title(value): def title(value):
"""Converts a string into titlecase.""" """Convert a string into titlecase."""
t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title()) t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title())
return re.sub(r"\d([A-Z])", lambda m: m.group(0).lower(), t) return re.sub(r"\d([A-Z])", lambda m: m.group(0).lower(), t)
@ -241,11 +239,7 @@ def title(value):
@register.filter(is_safe=True) @register.filter(is_safe=True)
@stringfilter @stringfilter
def truncatechars(value, arg): def truncatechars(value, arg):
""" """Truncate a string after `arg` number of characters."""
Truncates a string after a certain number of characters.
Argument: Number of characters to truncate after.
"""
try: try:
length = int(arg) length = int(arg)
except ValueError: # Invalid literal for int(). except ValueError: # Invalid literal for int().
@ -257,11 +251,8 @@ def truncatechars(value, arg):
@stringfilter @stringfilter
def truncatechars_html(value, arg): def truncatechars_html(value, arg):
""" """
Truncates HTML after a certain number of chars. Truncate HTML after `arg` number of chars.
Preserve newlines in the HTML.
Argument: Number of chars to truncate after.
Newlines in the HTML are preserved.
""" """
try: try:
length = int(arg) length = int(arg)
@ -274,11 +265,8 @@ def truncatechars_html(value, arg):
@stringfilter @stringfilter
def truncatewords(value, arg): def truncatewords(value, arg):
""" """
Truncates a string after a certain number of words. Truncate a string after `arg` number of words.
Remove newlines within the string.
Argument: Number of words to truncate after.
Newlines within the string are removed.
""" """
try: try:
length = int(arg) length = int(arg)
@ -291,11 +279,8 @@ def truncatewords(value, arg):
@stringfilter @stringfilter
def truncatewords_html(value, arg): def truncatewords_html(value, arg):
""" """
Truncates HTML after a certain number of words. Truncate HTML after `arg` number of words.
Preserve newlines in the HTML.
Argument: Number of words to truncate after.
Newlines in the HTML are preserved.
""" """
try: try:
length = int(arg) length = int(arg)
@ -307,7 +292,7 @@ def truncatewords_html(value, arg):
@register.filter(is_safe=False) @register.filter(is_safe=False)
@stringfilter @stringfilter
def upper(value): def upper(value):
"""Converts a string into all uppercase.""" """Convert a string into all uppercase."""
return value.upper() return value.upper()
@ -315,12 +300,12 @@ def upper(value):
@stringfilter @stringfilter
def urlencode(value, safe=None): def urlencode(value, safe=None):
""" """
Escapes a value for use in a URL. Escape a value for use in a URL.
Takes an optional ``safe`` parameter used to determine the characters which The ``safe`` parameter determines the characters which should not be
should not be escaped by Python's quote() function. If not provided, the escaped by Python's quote() function. If not provided, use the default safe
default safe characters will be used (but an empty string can be provided characters (but an empty string can be provided when *all* characters
when *all* characters should be escaped). should be escaped).
""" """
kwargs = {} kwargs = {}
if safe is not None: if safe is not None:
@ -331,7 +316,7 @@ def urlencode(value, safe=None):
@register.filter(is_safe=True, needs_autoescape=True) @register.filter(is_safe=True, needs_autoescape=True)
@stringfilter @stringfilter
def urlize(value, autoescape=True): def urlize(value, autoescape=True):
"""Converts URLs in plain text into clickable links.""" """Convert URLs in plain text into clickable links."""
return mark_safe(_urlize(value, nofollow=True, autoescape=autoescape)) return mark_safe(_urlize(value, nofollow=True, autoescape=autoescape))
@ -339,7 +324,7 @@ def urlize(value, autoescape=True):
@stringfilter @stringfilter
def urlizetrunc(value, limit, autoescape=True): def urlizetrunc(value, limit, autoescape=True):
""" """
Converts URLs into clickable links, truncating URLs to the given character Convert URLs into clickable links, truncating URLs to the given character
limit, and adding 'rel=nofollow' attribute to discourage spamming. limit, and adding 'rel=nofollow' attribute to discourage spamming.
Argument: Length to truncate URLs to. Argument: Length to truncate URLs to.
@ -350,56 +335,42 @@ def urlizetrunc(value, limit, autoescape=True):
@register.filter(is_safe=False) @register.filter(is_safe=False)
@stringfilter @stringfilter
def wordcount(value): def wordcount(value):
"""Returns the number of words.""" """Return the number of words."""
return len(value.split()) return len(value.split())
@register.filter(is_safe=True) @register.filter(is_safe=True)
@stringfilter @stringfilter
def wordwrap(value, arg): def wordwrap(value, arg):
""" """Wrap words at `arg` line length."""
Wraps words at specified line length.
Argument: number of characters to wrap the text at.
"""
return wrap(value, int(arg)) return wrap(value, int(arg))
@register.filter(is_safe=True) @register.filter(is_safe=True)
@stringfilter @stringfilter
def ljust(value, arg): def ljust(value, arg):
""" """Left-align the value in a field of a given width."""
Left-aligns the value in a field of a given width.
Argument: field size.
"""
return value.ljust(int(arg)) return value.ljust(int(arg))
@register.filter(is_safe=True) @register.filter(is_safe=True)
@stringfilter @stringfilter
def rjust(value, arg): def rjust(value, arg):
""" """Right-align the value in a field of a given width."""
Right-aligns the value in a field of a given width.
Argument: field size.
"""
return value.rjust(int(arg)) return value.rjust(int(arg))
@register.filter(is_safe=True) @register.filter(is_safe=True)
@stringfilter @stringfilter
def center(value, arg): def center(value, arg):
"""Centers the value in a field of a given width.""" """Center the value in a field of a given width."""
return value.center(int(arg)) return value.center(int(arg))
@register.filter @register.filter
@stringfilter @stringfilter
def cut(value, arg): def cut(value, arg):
""" """Remove all values of arg from the given string."""
Removes all values of arg from the given string.
"""
safe = isinstance(value, SafeData) safe = isinstance(value, SafeData)
value = value.replace(arg, '') value = value.replace(arg, '')
if safe and arg != ';': if safe and arg != ';':
@ -414,9 +385,7 @@ def cut(value, arg):
@register.filter("escape", is_safe=True) @register.filter("escape", is_safe=True)
@stringfilter @stringfilter
def escape_filter(value): def escape_filter(value):
""" """Mark the value as a string that should be auto-escaped."""
Marks the value as a string that should be auto-escaped.
"""
return conditional_escape(value) return conditional_escape(value)
@ -424,7 +393,7 @@ def escape_filter(value):
@stringfilter @stringfilter
def force_escape(value): def force_escape(value):
""" """
Escapes a string's HTML. This returns a new string containing the escaped Escape a string's HTML. Return a new string containing the escaped
characters (as opposed to "escape", which marks the content for later characters (as opposed to "escape", which marks the content for later
possible escaping). possible escaping).
""" """
@ -435,7 +404,7 @@ def force_escape(value):
@stringfilter @stringfilter
def linebreaks_filter(value, autoescape=True): def linebreaks_filter(value, autoescape=True):
""" """
Replaces line breaks in plain text with appropriate HTML; a single Replace line breaks in plain text with appropriate HTML; a single
newline becomes an HTML line break (``<br />``) and a new line newline becomes an HTML line break (``<br />``) and a new line
followed by a blank line becomes a paragraph break (``</p>``). followed by a blank line becomes a paragraph break (``</p>``).
""" """
@ -447,7 +416,7 @@ def linebreaks_filter(value, autoescape=True):
@stringfilter @stringfilter
def linebreaksbr(value, autoescape=True): def linebreaksbr(value, autoescape=True):
""" """
Converts all newlines in a piece of plain text to HTML line breaks Convert all newlines in a piece of plain text to HTML line breaks
(``<br />``). (``<br />``).
""" """
autoescape = autoescape and not isinstance(value, SafeData) autoescape = autoescape and not isinstance(value, SafeData)
@ -460,17 +429,15 @@ def linebreaksbr(value, autoescape=True):
@register.filter(is_safe=True) @register.filter(is_safe=True)
@stringfilter @stringfilter
def safe(value): def safe(value):
""" """Mark the value as a string that should not be auto-escaped."""
Marks the value as a string that should not be auto-escaped.
"""
return mark_safe(value) return mark_safe(value)
@register.filter(is_safe=True) @register.filter(is_safe=True)
def safeseq(value): def safeseq(value):
""" """
A "safe" filter for sequences. Marks each element in the sequence, A "safe" filter for sequences. Mark each element in the sequence,
individually, as safe, after converting them to strings. Returns a list individually, as safe, after converting them to strings. Return a list
with the results. with the results.
""" """
return [mark_safe(str(obj)) for obj in value] return [mark_safe(str(obj)) for obj in value]
@ -479,7 +446,7 @@ def safeseq(value):
@register.filter(is_safe=True) @register.filter(is_safe=True)
@stringfilter @stringfilter
def striptags(value): def striptags(value):
"""Strips all [X]HTML tags.""" """Strip all [X]HTML tags."""
return strip_tags(value) return strip_tags(value)
@ -516,7 +483,7 @@ def _property_resolver(arg):
@register.filter(is_safe=False) @register.filter(is_safe=False)
def dictsort(value, arg): def dictsort(value, arg):
""" """
Takes a list of dicts, returns that list sorted by the property given in Given a list of dicts, return that list sorted by the property given in
the argument. the argument.
""" """
try: try:
@ -528,7 +495,7 @@ def dictsort(value, arg):
@register.filter(is_safe=False) @register.filter(is_safe=False)
def dictsortreversed(value, arg): def dictsortreversed(value, arg):
""" """
Takes a list of dicts, returns that list sorted in reverse order by the Given a list of dicts, return that list sorted in reverse order by the
property given in the argument. property given in the argument.
""" """
try: try:
@ -539,7 +506,7 @@ def dictsortreversed(value, arg):
@register.filter(is_safe=False) @register.filter(is_safe=False)
def first(value): def first(value):
"""Returns the first item in a list.""" """Return the first item in a list."""
try: try:
return value[0] return value[0]
except IndexError: except IndexError:
@ -548,9 +515,7 @@ def first(value):
@register.filter(is_safe=True, needs_autoescape=True) @register.filter(is_safe=True, needs_autoescape=True)
def join(value, arg, autoescape=True): def join(value, arg, autoescape=True):
""" """Join a list with a string, like Python's ``str.join(list)``."""
Joins a list with a string, like Python's ``str.join(list)``.
"""
if autoescape: if autoescape:
value = [conditional_escape(v) for v in value] value = [conditional_escape(v) for v in value]
try: try:
@ -562,7 +527,7 @@ def join(value, arg, autoescape=True):
@register.filter(is_safe=True) @register.filter(is_safe=True)
def last(value): def last(value):
"Returns the last item in a list" """Return the last item in a list."""
try: try:
return value[-1] return value[-1]
except IndexError: except IndexError:
@ -571,7 +536,7 @@ def last(value):
@register.filter(is_safe=False) @register.filter(is_safe=False)
def length(value): def length(value):
"""Returns the length of the value - useful for lists.""" """Return the length of the value - useful for lists."""
try: try:
return len(value) return len(value)
except (ValueError, TypeError): except (ValueError, TypeError):
@ -580,7 +545,7 @@ def length(value):
@register.filter(is_safe=False) @register.filter(is_safe=False)
def length_is(value, arg): def length_is(value, arg):
"""Returns a boolean of whether the value's length is the argument.""" """Return a boolean of whether the value's length is the argument."""
try: try:
return len(value) == int(arg) return len(value) == int(arg)
except (ValueError, TypeError): except (ValueError, TypeError):
@ -589,18 +554,14 @@ def length_is(value, arg):
@register.filter(is_safe=True) @register.filter(is_safe=True)
def random(value): def random(value):
"""Returns a random item from the list.""" """Return a random item from the list."""
return random_module.choice(value) return random_module.choice(value)
@register.filter("slice", is_safe=True) @register.filter("slice", is_safe=True)
def slice_filter(value, arg): def slice_filter(value, arg):
""" """
Returns a slice of the list. Return a slice of the list using the same syntax as Python's list slicing.
Uses the same syntax as Python's list slicing; see
http://www.diveintopython3.net/native-datatypes.html#slicinglists
for an introduction.
""" """
try: try:
bits = [] bits = []
@ -618,12 +579,12 @@ def slice_filter(value, arg):
@register.filter(is_safe=True, needs_autoescape=True) @register.filter(is_safe=True, needs_autoescape=True)
def unordered_list(value, autoescape=True): def unordered_list(value, autoescape=True):
""" """
Recursively takes a self-nested list and returns an HTML unordered list -- Recursively take a self-nested list and return an HTML unordered list --
WITHOUT opening and closing <ul> tags. WITHOUT opening and closing <ul> tags.
The list is assumed to be in the proper format. For example, if ``var`` Assume the list is in the proper format. For example, if ``var`` contains:
contains: ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then
then ``{{ var|unordered_list }}`` would return:: ``{{ var|unordered_list }}`` returns::
<li>States <li>States
<ul> <ul>
@ -688,7 +649,7 @@ def unordered_list(value, autoescape=True):
@register.filter(is_safe=False) @register.filter(is_safe=False)
def add(value, arg): def add(value, arg):
"""Adds the arg to the value.""" """Add the arg to the value."""
try: try:
return int(value) + int(arg) return int(value) + int(arg)
except (ValueError, TypeError): except (ValueError, TypeError):
@ -701,8 +662,8 @@ def add(value, arg):
@register.filter(is_safe=False) @register.filter(is_safe=False)
def get_digit(value, arg): def get_digit(value, arg):
""" """
Given a whole number, returns the requested digit of it, where 1 is the Given a whole number, return the requested digit of it, where 1 is the
right-most digit, 2 is the second-right-most digit, etc. Returns the right-most digit, 2 is the second-right-most digit, etc. Return the
original value for invalid input (if input or argument is not an integer, original value for invalid input (if input or argument is not an integer,
or if argument is less than 1). Otherwise, output is always an integer. or if argument is less than 1). Otherwise, output is always an integer.
""" """
@ -725,7 +686,7 @@ def get_digit(value, arg):
@register.filter(expects_localtime=True, is_safe=False) @register.filter(expects_localtime=True, is_safe=False)
def date(value, arg=None): def date(value, arg=None):
"""Formats a date according to the given format.""" """Format a date according to the given format."""
if value in (None, ''): if value in (None, ''):
return '' return ''
try: try:
@ -739,7 +700,7 @@ def date(value, arg=None):
@register.filter(expects_localtime=True, is_safe=False) @register.filter(expects_localtime=True, is_safe=False)
def time(value, arg=None): def time(value, arg=None):
"""Formats a time according to the given format.""" """Format a time according to the given format."""
if value in (None, ''): if value in (None, ''):
return '' return ''
try: try:
@ -753,7 +714,7 @@ def time(value, arg=None):
@register.filter("timesince", is_safe=False) @register.filter("timesince", is_safe=False)
def timesince_filter(value, arg=None): def timesince_filter(value, arg=None):
"""Formats a date as the time since that date (i.e. "4 days, 6 hours").""" """Format a date as the time since that date (i.e. "4 days, 6 hours")."""
if not value: if not value:
return '' return ''
try: try:
@ -766,7 +727,7 @@ def timesince_filter(value, arg=None):
@register.filter("timeuntil", is_safe=False) @register.filter("timeuntil", is_safe=False)
def timeuntil_filter(value, arg=None): def timeuntil_filter(value, arg=None):
"""Formats a date as the time until that date (i.e. "4 days, 6 hours").""" """Format a date as the time until that date (i.e. "4 days, 6 hours")."""
if not value: if not value:
return '' return ''
try: try:
@ -795,15 +756,15 @@ def default_if_none(value, arg):
@register.filter(is_safe=False) @register.filter(is_safe=False)
def divisibleby(value, arg): def divisibleby(value, arg):
"""Returns True if the value is divisible by the argument.""" """Return True if the value is divisible by the argument."""
return int(value) % int(arg) == 0 return int(value) % int(arg) == 0
@register.filter(is_safe=False) @register.filter(is_safe=False)
def yesno(value, arg=None): def yesno(value, arg=None):
""" """
Given a string mapping values for true, false and (optionally) None, Given a string mapping values for true, false, and (optionally) None,
returns one of those strings according to the value: return one of those strings according to the value:
========== ====================== ================================== ========== ====================== ==================================
Value Argument Outputs Value Argument Outputs
@ -839,7 +800,7 @@ def yesno(value, arg=None):
@register.filter(is_safe=True) @register.filter(is_safe=True)
def filesizeformat(bytes_): def filesizeformat(bytes_):
""" """
Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
102 bytes, etc.). 102 bytes, etc.).
""" """
try: try:
@ -882,26 +843,25 @@ def filesizeformat(bytes_):
@register.filter(is_safe=False) @register.filter(is_safe=False)
def pluralize(value, arg='s'): def pluralize(value, arg='s'):
""" """
Returns a plural suffix if the value is not 1. By default, 's' is used as Return a plural suffix if the value is not 1. By default, use 's' as the
the suffix: suffix:
* If value is 0, vote{{ value|pluralize }} displays "0 votes". * If value is 0, vote{{ value|pluralize }} display "0 votes".
* If value is 1, vote{{ value|pluralize }} displays "1 vote". * If value is 1, vote{{ value|pluralize }} display "1 vote".
* If value is 2, vote{{ value|pluralize }} displays "2 votes". * If value is 2, vote{{ value|pluralize }} display "2 votes".
If an argument is provided, that string is used instead: If an argument is provided, use that string instead:
* If value is 0, class{{ value|pluralize:"es" }} displays "0 classes". * If value is 0, class{{ value|pluralize:"es" }} display "0 classes".
* If value is 1, class{{ value|pluralize:"es" }} displays "1 class". * If value is 1, class{{ value|pluralize:"es" }} display "1 class".
* If value is 2, class{{ value|pluralize:"es" }} displays "2 classes". * If value is 2, class{{ value|pluralize:"es" }} display "2 classes".
If the provided argument contains a comma, the text before the comma is If the provided argument contains a comma, use the text before the comma
used for the singular case and the text after the comma is used for the for the singular case and the text after the comma for the plural case:
plural case:
* If value is 0, cand{{ value|pluralize:"y,ies" }} displays "0 candies". * If value is 0, cand{{ value|pluralize:"y,ies" }} display "0 candies".
* If value is 1, cand{{ value|pluralize:"y,ies" }} displays "1 candy". * If value is 1, cand{{ value|pluralize:"y,ies" }} display "1 candy".
* If value is 2, cand{{ value|pluralize:"y,ies" }} displays "2 candies". * If value is 2, cand{{ value|pluralize:"y,ies" }} display "2 candies".
""" """
if ',' not in arg: if ',' not in arg:
arg = ',' + arg arg = ',' + arg
@ -926,7 +886,7 @@ def pluralize(value, arg='s'):
@register.filter("phone2numeric", is_safe=True) @register.filter("phone2numeric", is_safe=True)
def phone2numeric_filter(value): def phone2numeric_filter(value):
"""Takes a phone number and converts it in to its numerical equivalent.""" """Take a phone number and converts it in to its numerical equivalent."""
return phone2numeric(value) return phone2numeric(value)

View File

@ -27,7 +27,7 @@ register = Library()
class AutoEscapeControlNode(Node): class AutoEscapeControlNode(Node):
"""Implements the actions of the autoescape tag.""" """Implement the actions of the autoescape tag."""
def __init__(self, setting, nodelist): def __init__(self, setting, nodelist):
self.setting, self.nodelist = setting, nodelist self.setting, self.nodelist = setting, nodelist
@ -542,7 +542,7 @@ def autoescape(parser, token):
@register.tag @register.tag
def comment(parser, token): def comment(parser, token):
""" """
Ignores everything between ``{% comment %}`` and ``{% endcomment %}``. Ignore everything between ``{% comment %}`` and ``{% endcomment %}``.
""" """
parser.skip_past('endcomment') parser.skip_past('endcomment')
return CommentNode() return CommentNode()
@ -551,7 +551,7 @@ def comment(parser, token):
@register.tag @register.tag
def cycle(parser, token): def cycle(parser, token):
""" """
Cycles among the given strings each time this tag is encountered. Cycle among the given strings each time this tag is encountered.
Within a loop, cycles among the given strings each time through Within a loop, cycles among the given strings each time through
the loop:: the loop::
@ -644,7 +644,7 @@ def csrf_token(parser, token):
@register.tag @register.tag
def debug(parser, token): def debug(parser, token):
""" """
Outputs a whole load of debugging information, including the current Output a whole load of debugging information, including the current
context and imported modules. context and imported modules.
Sample usage:: Sample usage::
@ -659,7 +659,7 @@ def debug(parser, token):
@register.tag('filter') @register.tag('filter')
def do_filter(parser, token): def do_filter(parser, token):
""" """
Filters the contents of the block through variable filters. Filter the contents of the block through variable filters.
Filters can also be piped through each other, and they can have Filters can also be piped through each other, and they can have
arguments -- just like in variable syntax. arguments -- just like in variable syntax.
@ -689,9 +689,9 @@ def do_filter(parser, token):
@register.tag @register.tag
def firstof(parser, token): def firstof(parser, token):
""" """
Outputs the first variable passed that is not False. Output the first variable passed that is not False.
Outputs nothing if all the passed variables are False. Output nothing if all the passed variables are False.
Sample usage:: Sample usage::
@ -738,7 +738,7 @@ def firstof(parser, token):
@register.tag('for') @register.tag('for')
def do_for(parser, token): def do_for(parser, token):
""" """
Loops over each item in an array. Loop over each item in an array.
For example, to display a list of athletes given ``athlete_list``:: For example, to display a list of athletes given ``athlete_list``::
@ -847,7 +847,7 @@ def do_ifequal(parser, token, negate):
@register.tag @register.tag
def ifequal(parser, token): def ifequal(parser, token):
""" """
Outputs the contents of the block if the two arguments equal each other. Output the contents of the block if the two arguments equal each other.
Examples:: Examples::
@ -867,7 +867,7 @@ def ifequal(parser, token):
@register.tag @register.tag
def ifnotequal(parser, token): def ifnotequal(parser, token):
""" """
Outputs the contents of the block if the two arguments are not equal. Output the contents of the block if the two arguments are not equal.
See ifequal. See ifequal.
""" """
return do_ifequal(parser, token, True) return do_ifequal(parser, token, True)
@ -899,9 +899,8 @@ class TemplateIfParser(IfParser):
@register.tag('if') @register.tag('if')
def do_if(parser, token): def do_if(parser, token):
""" """
The ``{% if %}`` tag evaluates a variable, and if that variable is "true" Evaluate a variable, and if that variable is "true" (i.e., exists, is not
(i.e., exists, is not empty, and is not a false boolean value), the empty, and is not a false boolean value), output the contents of the block:
contents of the block are output:
:: ::
@ -916,9 +915,9 @@ def do_if(parser, token):
In the above, if ``athlete_list`` is not empty, the number of athletes will In the above, if ``athlete_list`` is not empty, the number of athletes will
be displayed by the ``{{ athlete_list|count }}`` variable. be displayed by the ``{{ athlete_list|count }}`` variable.
As you can see, the ``if`` tag may take one or several `` {% elif %}`` The ``if`` tag may take one or several `` {% elif %}`` clauses, as well as
clauses, as well as an ``{% else %}`` clause that will be displayed if all an ``{% else %}`` clause that will be displayed if all previous conditions
previous conditions fail. These clauses are optional. fail. These clauses are optional.
``if`` tags may use ``or``, ``and`` or ``not`` to test a number of ``if`` tags may use ``or``, ``and`` or ``not`` to test a number of
variables or to negate a given variable:: variables or to negate a given variable::
@ -987,12 +986,12 @@ def do_if(parser, token):
@register.tag @register.tag
def ifchanged(parser, token): def ifchanged(parser, token):
""" """
Checks if a value has changed from the last iteration of a loop. Check if a value has changed from the last iteration of a loop.
The ``{% ifchanged %}`` block tag is used within a loop. It has two The ``{% ifchanged %}`` block tag is used within a loop. It has two
possible uses. possible uses.
1. Checks its own rendered contents against its previous state and only 1. Check its own rendered contents against its previous state and only
displays the content if it has changed. For example, this displays a displays the content if it has changed. For example, this displays a
list of days, only displaying the month if it changes:: list of days, only displaying the month if it changes::
@ -1062,7 +1061,7 @@ def load_from_library(library, label, names):
@register.tag @register.tag
def load(parser, token): def load(parser, token):
""" """
Loads a custom template tag library into the parser. Load a custom template tag library into the parser.
For example, to load the template tags in For example, to load the template tags in
``django/templatetags/news/photos.py``:: ``django/templatetags/news/photos.py``::
@ -1093,7 +1092,7 @@ def load(parser, token):
@register.tag @register.tag
def lorem(parser, token): def lorem(parser, token):
""" """
Creates random Latin text useful for providing test data in templates. Create random Latin text useful for providing test data in templates.
Usage format:: Usage format::
@ -1110,10 +1109,10 @@ def lorem(parser, token):
Examples: Examples:
* ``{% lorem %}`` will output the common "lorem ipsum" paragraph * ``{% lorem %}`` outputs the common "lorem ipsum" paragraph
* ``{% lorem 3 p %}`` will output the common "lorem ipsum" paragraph * ``{% lorem 3 p %}`` outputs the common "lorem ipsum" paragraph
and two random paragraphs each wrapped in HTML ``<p>`` tags and two random paragraphs each wrapped in HTML ``<p>`` tags
* ``{% lorem 2 w random %}`` will output two random latin words * ``{% lorem 2 w random %}`` outputs two random latin words
""" """
bits = list(token.split_contents()) bits = list(token.split_contents())
tagname = bits[0] tagname = bits[0]
@ -1140,9 +1139,9 @@ def lorem(parser, token):
@register.tag @register.tag
def now(parser, token): def now(parser, token):
""" """
Displays the date, formatted according to the given string. Display the date, formatted according to the given string.
Uses the same format as PHP's ``date()`` function; see http://php.net/date Use the same format as PHP's ``date()`` function; see http://php.net/date
for all the possible values. for all the possible values.
Sample usage:: Sample usage::
@ -1163,7 +1162,7 @@ def now(parser, token):
@register.tag @register.tag
def regroup(parser, token): def regroup(parser, token):
""" """
Regroups a list of alike objects by a common attribute. Regroup a list of alike objects by a common attribute.
This complex tag is best illustrated by use of an example: say that This complex tag is best illustrated by use of an example: say that
``musicians`` is a list of ``Musician`` objects that have ``name`` and ``musicians`` is a list of ``Musician`` objects that have ``name`` and
@ -1232,10 +1231,10 @@ def regroup(parser, token):
@register.tag @register.tag
def resetcycle(parser, token): def resetcycle(parser, token):
""" """
Resets a cycle tag. Reset a cycle tag.
If an argument is given, resets the last rendered cycle tag whose name If an argument is given, reset the last rendered cycle tag whose name
matches the argument, else resets the last rendered cycle tag (named or matches the argument, else reset the last rendered cycle tag (named or
unnamed). unnamed).
""" """
args = token.split_contents() args = token.split_contents()
@ -1258,7 +1257,7 @@ def resetcycle(parser, token):
@register.tag @register.tag
def spaceless(parser, token): def spaceless(parser, token):
""" """
Removes whitespace between HTML tags, including tab and newline characters. Remove whitespace between HTML tags, including tab and newline characters.
Example usage:: Example usage::
@ -1268,12 +1267,12 @@ def spaceless(parser, token):
</p> </p>
{% endspaceless %} {% endspaceless %}
This example would return this HTML:: This example returns this HTML::
<p><a href="foo/">Foo</a></p> <p><a href="foo/">Foo</a></p>
Only space between *tags* is normalized -- not space between tags and text. Only space between *tags* is normalized -- not space between tags and text.
In this example, the space around ``Hello`` won't be stripped:: In this example, the space around ``Hello`` isn't stripped::
{% spaceless %} {% spaceless %}
<strong> <strong>
@ -1289,7 +1288,7 @@ def spaceless(parser, token):
@register.tag @register.tag
def templatetag(parser, token): def templatetag(parser, token):
""" """
Outputs one of the bits used to compose template tags. Output one of the bits used to compose template tags.
Since the template system has no concept of "escaping", to display one of Since the template system has no concept of "escaping", to display one of
the bits used in template tags, you must use the ``{% templatetag %}`` tag. the bits used in template tags, you must use the ``{% templatetag %}`` tag.
@ -1392,7 +1391,7 @@ def url(parser, token):
@register.tag @register.tag
def verbatim(parser, token): def verbatim(parser, token):
""" """
Stops the template engine from rendering the contents of this block tag. Stop the template engine from rendering the contents of this block tag.
Usage:: Usage::
@ -1415,8 +1414,8 @@ def verbatim(parser, token):
@register.tag @register.tag
def widthratio(parser, token): def widthratio(parser, token):
""" """
For creating bar charts and such, this tag calculates the ratio of a given For creating bar charts and such. Calculate the ratio of a given value to a
value to a maximum value, and then applies that ratio to a constant. maximum value, and then apply that ratio to a constant.
For example:: For example::
@ -1453,7 +1452,7 @@ def widthratio(parser, token):
@register.tag('with') @register.tag('with')
def do_with(parser, token): def do_with(parser, token):
""" """
Adds one or more values to the context (inside of this block) for caching Add one or more values to the context (inside of this block) for caching
and easy access. and easy access.
For example:: For example::

View File

@ -56,9 +56,9 @@ class Engine:
@functools.lru_cache() @functools.lru_cache()
def get_default(): def get_default():
""" """
When only one DjangoTemplates backend is configured, returns it. When only one DjangoTemplates backend is configured, return it.
Raises ImproperlyConfigured otherwise. Raise ImproperlyConfigured otherwise.
This is required for preserving historical APIs that rely on a This is required for preserving historical APIs that rely on a
globally available, implicitly configured engine such as: globally available, implicitly configured engine such as:
@ -140,14 +140,14 @@ class Engine:
def from_string(self, template_code): def from_string(self, template_code):
""" """
Returns a compiled Template object for the given template code, Return a compiled Template object for the given template code,
handling template inheritance recursively. handling template inheritance recursively.
""" """
return Template(template_code, engine=self) return Template(template_code, engine=self)
def get_template(self, template_name): def get_template(self, template_name):
""" """
Returns a compiled Template object for the given template name, Return a compiled Template object for the given template name,
handling template inheritance recursively. handling template inheritance recursively.
""" """
template, origin = self.find_template(template_name) template, origin = self.find_template(template_name)
@ -174,7 +174,7 @@ class Engine:
def select_template(self, template_name_list): def select_template(self, template_name_list):
""" """
Given a list of template names, returns the first that can be loaded. Given a list of template names, return the first that can be loaded.
""" """
if not template_name_list: if not template_name_list:
raise TemplateDoesNotExist("No template names provided") raise TemplateDoesNotExist("No template names provided")

View File

@ -8,8 +8,7 @@ here.
class TemplateDoesNotExist(Exception): class TemplateDoesNotExist(Exception):
""" """
The exception used when a template does not exist. Accepts the following The exception used when a template does not exist. Optional arguments:
optional arguments:
backend backend
The template backend class used when raising this exception. The template backend class used when raising this exception.

View File

@ -4,9 +4,9 @@ from .exceptions import TemplateDoesNotExist
def get_template(template_name, using=None): def get_template(template_name, using=None):
""" """
Loads and returns a template for the given name. Load and return a template for the given name.
Raises TemplateDoesNotExist if no such template exists. Raise TemplateDoesNotExist if no such template exists.
""" """
chain = [] chain = []
engines = _engine_list(using) engines = _engine_list(using)
@ -21,11 +21,11 @@ def get_template(template_name, using=None):
def select_template(template_name_list, using=None): def select_template(template_name_list, using=None):
""" """
Loads and returns a template for one of the given names. Load and return a template for one of the given names.
Tries names in order and returns the first template found. Try names in order and return the first template found.
Raises TemplateDoesNotExist if no such template exists. Raise TemplateDoesNotExist if no such template exists.
""" """
if isinstance(template_name_list, str): if isinstance(template_name_list, str):
raise TypeError( raise TypeError(
@ -51,7 +51,7 @@ def select_template(template_name_list, using=None):
def render_to_string(template_name, context=None, request=None, using=None): def render_to_string(template_name, context=None, request=None, using=None):
""" """
Loads a template and renders it with a context. Returns a string. Load a template and render it with a context. Return a string.
template_name may be a string or a list of strings. template_name may be a string or a list of strings.
""" """

View File

@ -295,7 +295,7 @@ def do_extends(parser, token):
@register.tag('include') @register.tag('include')
def do_include(parser, token): def do_include(parser, token):
""" """
Loads a template and renders it with the current context. You can pass Load a template and render it with the current context. You can pass
additional context using keyword arguments. additional context using keyword arguments.
Example:: Example::

View File

@ -8,10 +8,10 @@ class Loader:
def get_template(self, template_name, skip=None): def get_template(self, template_name, skip=None):
""" """
Calls self.get_template_sources() and returns a Template object for Call self.get_template_sources() and return a Template object for
the first template matching template_name. If skip is provided, the first template matching template_name. If skip is provided, ignore
template origins in skip are ignored. This is used to avoid recursion template origins in skip. This is used to avoid recursion during
during template extending. template extending.
""" """
tried = [] tried = []
@ -43,7 +43,7 @@ class Loader:
def reset(self): def reset(self):
""" """
Resets any state maintained by the loader instance (e.g. cached Reset any state maintained by the loader instance (e.g. cached
templates or cached loader modules). templates or cached loader modules).
""" """
pass pass

View File

@ -58,7 +58,7 @@ class SimpleTemplateResponse(HttpResponse):
return obj_dict return obj_dict
def resolve_template(self, template): def resolve_template(self, template):
"Accepts a template object, path-to-template or list of paths" """Accept a template object, path-to-template, or list of paths."""
if isinstance(template, (list, tuple)): if isinstance(template, (list, tuple)):
return select_template(template, using=self.using) return select_template(template, using=self.using)
elif isinstance(template, str): elif isinstance(template, str):
@ -71,7 +71,7 @@ class SimpleTemplateResponse(HttpResponse):
@property @property
def rendered_content(self): def rendered_content(self):
"""Returns the freshly rendered content for the template and context """Return the freshly rendered content for the template and context
described by the TemplateResponse. described by the TemplateResponse.
This *does not* set the final content of the response. To set the This *does not* set the final content of the response. To set the
@ -84,7 +84,7 @@ class SimpleTemplateResponse(HttpResponse):
return content return content
def add_post_render_callback(self, callback): def add_post_render_callback(self, callback):
"""Adds a new post-rendering callback. """Add a new post-rendering callback.
If the response has already been rendered, If the response has already been rendered,
invoke the callback immediately. invoke the callback immediately.
@ -95,11 +95,11 @@ class SimpleTemplateResponse(HttpResponse):
self._post_render_callbacks.append(callback) self._post_render_callbacks.append(callback)
def render(self): def render(self):
"""Renders (thereby finalizing) the content of the response. """Render (thereby finalizing) the content of the response.
If the content has already been rendered, this is a no-op. If the content has already been rendered, this is a no-op.
Returns the baked response instance. Return the baked response instance.
""" """
retval = self retval = self
if not self._is_rendered: if not self._is_rendered:
@ -131,8 +131,7 @@ class SimpleTemplateResponse(HttpResponse):
@content.setter @content.setter
def content(self, value): def content(self, value):
"""Sets the content for the response """Set the content for the response."""
"""
HttpResponse.content.fset(self, value) HttpResponse.content.fset(self, value)
self._is_rendered = True self._is_rendered = True

View File

@ -31,7 +31,7 @@ class TokenBase:
def display(self): def display(self):
""" """
Returns what to display in error messages for this node Return what to display in error messages for this node
""" """
return self.id return self.id
@ -42,8 +42,8 @@ class TokenBase:
def infix(bp, func): def infix(bp, func):
""" """
Creates an infix operator, given a binding power and a function that Create an infix operator, given a binding power and a function that
evaluates the node evaluates the node.
""" """
class Operator(TokenBase): class Operator(TokenBase):
lbp = bp lbp = bp
@ -67,7 +67,7 @@ def infix(bp, func):
def prefix(bp, func): def prefix(bp, func):
""" """
Creates a prefix operator, given a binding power and a function that Create a prefix operator, given a binding power and a function that
evaluates the node. evaluates the node.
""" """
class Operator(TokenBase): class Operator(TokenBase):

View File

@ -7,7 +7,7 @@ register = Library()
@register.filter(is_safe=False) @register.filter(is_safe=False)
def localize(value): def localize(value):
""" """
Forces a value to be rendered as a localized value, Force a value to be rendered as a localized value,
regardless of the value of ``settings.USE_L10N``. regardless of the value of ``settings.USE_L10N``.
""" """
return str(formats.localize(value, use_l10n=True)) return str(formats.localize(value, use_l10n=True))
@ -16,7 +16,7 @@ def localize(value):
@register.filter(is_safe=False) @register.filter(is_safe=False)
def unlocalize(value): def unlocalize(value):
""" """
Forces a value to be rendered as a non-localized value, Force a value to be rendered as a non-localized value,
regardless of the value of ``settings.USE_L10N``. regardless of the value of ``settings.USE_L10N``.
""" """
return str(value) return str(value)
@ -41,7 +41,7 @@ class LocalizeNode(Node):
@register.tag('localize') @register.tag('localize')
def localize_tag(parser, token): def localize_tag(parser, token):
""" """
Forces or prevents localization of values, regardless of the value of Force or prevents localization of values, regardless of the value of
`settings.USE_L10N`. `settings.USE_L10N`.
Sample usage:: Sample usage::

View File

@ -57,7 +57,7 @@ class PrefixNode(template.Node):
@register.tag @register.tag
def get_static_prefix(parser, token): def get_static_prefix(parser, token):
""" """
Populates a template variable with the static prefix, Populate a template variable with the static prefix,
``settings.STATIC_URL``. ``settings.STATIC_URL``.
Usage:: Usage::
@ -75,7 +75,7 @@ def get_static_prefix(parser, token):
@register.tag @register.tag
def get_media_prefix(parser, token): def get_media_prefix(parser, token):
""" """
Populates a template variable with the media prefix, Populate a template variable with the media prefix,
``settings.MEDIA_URL``. ``settings.MEDIA_URL``.
Usage:: Usage::
@ -143,7 +143,7 @@ class StaticNode(template.Node):
@register.tag('static') @register.tag('static')
def do_static(parser, token): def do_static(parser, token):
""" """
Joins the given path with the STATIC_URL setting. Join the given path with the STATIC_URL setting.
Usage:: Usage::

View File

@ -19,7 +19,7 @@ class datetimeobject(datetime):
@register.filter @register.filter
def localtime(value): def localtime(value):
""" """
Converts a datetime to local time in the active time zone. Convert a datetime to local time in the active time zone.
This only makes sense within a {% localtime off %} block. This only makes sense within a {% localtime off %} block.
""" """
@ -29,7 +29,7 @@ def localtime(value):
@register.filter @register.filter
def utc(value): def utc(value):
""" """
Converts a datetime to UTC. Convert a datetime to UTC.
""" """
return do_timezone(value, timezone.utc) return do_timezone(value, timezone.utc)
@ -37,7 +37,7 @@ def utc(value):
@register.filter('timezone') @register.filter('timezone')
def do_timezone(value, arg): def do_timezone(value, arg):
""" """
Converts a datetime to local time in a given time zone. Convert a datetime to local time in a given time zone.
The argument must be an instance of a tzinfo subclass or a time zone name. The argument must be an instance of a tzinfo subclass or a time zone name.
@ -125,7 +125,7 @@ class GetCurrentTimezoneNode(Node):
@register.tag('localtime') @register.tag('localtime')
def localtime_tag(parser, token): def localtime_tag(parser, token):
""" """
Forces or prevents conversion of datetime objects to local time, Force or prevent conversion of datetime objects to local time,
regardless of the value of ``settings.USE_TZ``. regardless of the value of ``settings.USE_TZ``.
Sample usage:: Sample usage::
@ -148,7 +148,7 @@ def localtime_tag(parser, token):
@register.tag('timezone') @register.tag('timezone')
def timezone_tag(parser, token): def timezone_tag(parser, token):
""" """
Enables a given time zone just for this block. Enable a given time zone just for this block.
The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
time zone name, or ``None``. If it is ``None``, the default time zone is time zone name, or ``None``. If it is ``None``, the default time zone is
@ -173,7 +173,7 @@ def timezone_tag(parser, token):
@register.tag("get_current_timezone") @register.tag("get_current_timezone")
def get_current_timezone_tag(parser, token): def get_current_timezone_tag(parser, token):
""" """
Stores the name of the current time zone in the context. Store the name of the current time zone in the context.
Usage:: Usage::