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):
"""
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()
self.name = params.pop('NAME')
@ -33,7 +33,7 @@ class BaseEngine:
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.
"""
@ -43,9 +43,9 @@ class BaseEngine:
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(
"subclasses of BaseEngine must provide "
@ -57,7 +57,7 @@ class BaseEngine:
@cached_property
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.
template_dirs = tuple(self.dirs)
@ -67,9 +67,9 @@ class BaseEngine:
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.
"""
for template_dir in self.template_dirs:

View File

@ -83,7 +83,7 @@ class Origin:
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.
"""
context_lines = 10

View File

@ -391,7 +391,7 @@ class DebugLexer(Lexer):
"""
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
lexer so we only use it when debug is True.
lexer so only use it when debug is True.
"""
lineno = 1
result = []
@ -616,7 +616,7 @@ filter_re = re.compile(filter_raw_string, re.VERBOSE)
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.
Sample::
@ -823,7 +823,7 @@ class Variable:
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.
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):
"""
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
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):
"""
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)
that is to be checked for arguments. Valid arguments will be removed
from this list.
:param support_legacy: If set to true ``True``, the legacy format
``1 as foo`` will be accepted. Otherwise, only the standard ``foo=1``
format is allowed.
:returns: A dictionary of the arguments retrieved from the ``bits`` token
`bits` is a list containing the remainder of the token (split by spaces)
that is to be checked for arguments. Valid arguments are removed from this
list.
`support_legacy` - if True, the legacy format ``1 as foo`` is accepted.
Otherwise, only the standard ``foo=1`` format is allowed.
There is no requirement for all remaining token ``bits`` to be keyword
arguments, so the dictionary will be returned as soon as an invalid
argument format is reached.
arguments, so return the dictionary as soon as an invalid argument format
is reached.
"""
if not bits:
return {}

View File

@ -108,7 +108,7 @@ class BaseContext:
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.
"""
new_context = copy(self)
@ -117,7 +117,7 @@ class BaseContext:
def flatten(self):
"""
Returns self.dicts as one dictionary
Return self.dicts as one dictionary.
"""
flat = {}
for d in self.dicts:
@ -126,7 +126,7 @@ class BaseContext:
def __eq__(self, other):
"""
Compares two contexts by comparing theirs 'dicts' attributes.
Compare two contexts by comparing theirs 'dicts' attributes.
"""
if isinstance(other, BaseContext):
# because dictionaries can be put in different order
@ -166,7 +166,7 @@ class Context(BaseContext):
return duplicate
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__'):
raise TypeError('other_dict must be a mapping (dictionary-like) object.')
if isinstance(other_dict, BaseContext):

View File

@ -34,7 +34,7 @@ def csrf(request):
def debug(request):
"""
Returns context variables helpful for debugging.
Return context variables helpful for debugging.
"""
context_extras = {}
if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
@ -65,14 +65,14 @@ def tz(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}
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}

View File

@ -61,7 +61,7 @@ def stringfilter(func):
@stringfilter
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``
filter instead.
"""
@ -71,24 +71,24 @@ def addslashes(value):
@register.filter(is_safe=True)
@stringfilter
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:]
@register.filter("escapejs")
@stringfilter
def escapejs_filter(value):
"""Hex encodes characters for use in JavaScript strings."""
"""Hex encode characters for use in JavaScript strings."""
return escapejs(value)
@register.filter(is_safe=True)
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
one decimal place -- but only if there's a decimal place to be displayed:
If called without an argument, display the floating point number with one
decimal place -- but only if there's a decimal place to be displayed:
* num1 = 34.23234
* num2 = 34.00000
@ -97,24 +97,22 @@ def floatformat(text, arg=-1):
* {{ num2|floatformat }} displays "34"
* {{ num3|floatformat }} displays "34.3"
If arg is positive, it will always display exactly arg number of decimal
places:
If arg is positive, always display exactly arg number of decimal places:
* {{ num1|floatformat:3 }} displays "34.232"
* {{ num2|floatformat:3 }} displays "34.000"
* {{ num3|floatformat:3 }} displays "34.260"
If arg is negative, it will display arg number of decimal places -- but
only if there are places to be displayed:
If arg is negative, display arg number of decimal places -- but only if
there are places to be displayed:
* {{ num1|floatformat:"-3" }} displays "34.232"
* {{ num2|floatformat:"-3" }} displays "34"
* {{ num3|floatformat:"-3" }} displays "34.260"
If the input float is infinity or NaN, the (platform-dependent) string
representation of that value will be displayed.
If the input float is infinity or NaN, display the string representation
of that value.
"""
try:
input_val = repr(text)
d = Decimal(input_val)
@ -162,14 +160,14 @@ def floatformat(text, arg=-1):
@register.filter(is_safe=True)
@stringfilter
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)
@register.filter(is_safe=True, needs_autoescape=True)
@stringfilter
def linenumbers(value, autoescape=True):
"""Displays text with line numbers."""
"""Display text with line numbers."""
lines = value.split('\n')
# Find the maximum width of the line count, for use with zero padding
# string format command
@ -186,7 +184,7 @@ def linenumbers(value, autoescape=True):
@register.filter(is_safe=True)
@stringfilter
def lower(value):
"""Converts a string into all lowercase."""
"""Convert a string into all lowercase."""
return value.lower()
@ -194,7 +192,7 @@ def lower(value):
@stringfilter
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 a string, it's a list of characters.
@ -206,9 +204,9 @@ def make_list(value):
@stringfilter
def slugify(value):
"""
Converts to ASCII. Converts spaces to hyphens. Removes characters that
aren't alphanumerics, underscores, or hyphens. Converts to lowercase.
Also strips leading and trailing whitespace.
Convert to ASCII. Convert spaces to hyphens. Remove characters that aren't
alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip
leading and trailing whitespace.
"""
return _slugify(value)
@ -216,7 +214,7 @@ def slugify(value):
@register.filter(is_safe=True)
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
the leading "%" is dropped.
@ -233,7 +231,7 @@ def stringformat(value, arg):
@register.filter(is_safe=True)
@stringfilter
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())
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)
@stringfilter
def truncatechars(value, arg):
"""
Truncates a string after a certain number of characters.
Argument: Number of characters to truncate after.
"""
"""Truncate a string after `arg` number of characters."""
try:
length = int(arg)
except ValueError: # Invalid literal for int().
@ -257,11 +251,8 @@ def truncatechars(value, arg):
@stringfilter
def truncatechars_html(value, arg):
"""
Truncates HTML after a certain number of chars.
Argument: Number of chars to truncate after.
Newlines in the HTML are preserved.
Truncate HTML after `arg` number of chars.
Preserve newlines in the HTML.
"""
try:
length = int(arg)
@ -274,11 +265,8 @@ def truncatechars_html(value, arg):
@stringfilter
def truncatewords(value, arg):
"""
Truncates a string after a certain number of words.
Argument: Number of words to truncate after.
Newlines within the string are removed.
Truncate a string after `arg` number of words.
Remove newlines within the string.
"""
try:
length = int(arg)
@ -291,11 +279,8 @@ def truncatewords(value, arg):
@stringfilter
def truncatewords_html(value, arg):
"""
Truncates HTML after a certain number of words.
Argument: Number of words to truncate after.
Newlines in the HTML are preserved.
Truncate HTML after `arg` number of words.
Preserve newlines in the HTML.
"""
try:
length = int(arg)
@ -307,7 +292,7 @@ def truncatewords_html(value, arg):
@register.filter(is_safe=False)
@stringfilter
def upper(value):
"""Converts a string into all uppercase."""
"""Convert a string into all uppercase."""
return value.upper()
@ -315,12 +300,12 @@ def upper(value):
@stringfilter
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
should not be escaped by Python's quote() function. If not provided, the
default safe characters will be used (but an empty string can be provided
when *all* characters should be escaped).
The ``safe`` parameter determines the characters which should not be
escaped by Python's quote() function. If not provided, use the default safe
characters (but an empty string can be provided when *all* characters
should be escaped).
"""
kwargs = {}
if safe is not None:
@ -331,7 +316,7 @@ def urlencode(value, safe=None):
@register.filter(is_safe=True, needs_autoescape=True)
@stringfilter
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))
@ -339,7 +324,7 @@ def urlize(value, autoescape=True):
@stringfilter
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.
Argument: Length to truncate URLs to.
@ -350,56 +335,42 @@ def urlizetrunc(value, limit, autoescape=True):
@register.filter(is_safe=False)
@stringfilter
def wordcount(value):
"""Returns the number of words."""
"""Return the number of words."""
return len(value.split())
@register.filter(is_safe=True)
@stringfilter
def wordwrap(value, arg):
"""
Wraps words at specified line length.
Argument: number of characters to wrap the text at.
"""
"""Wrap words at `arg` line length."""
return wrap(value, int(arg))
@register.filter(is_safe=True)
@stringfilter
def ljust(value, arg):
"""
Left-aligns the value in a field of a given width.
Argument: field size.
"""
"""Left-align the value in a field of a given width."""
return value.ljust(int(arg))
@register.filter(is_safe=True)
@stringfilter
def rjust(value, arg):
"""
Right-aligns the value in a field of a given width.
Argument: field size.
"""
"""Right-align the value in a field of a given width."""
return value.rjust(int(arg))
@register.filter(is_safe=True)
@stringfilter
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))
@register.filter
@stringfilter
def cut(value, arg):
"""
Removes all values of arg from the given string.
"""
"""Remove all values of arg from the given string."""
safe = isinstance(value, SafeData)
value = value.replace(arg, '')
if safe and arg != ';':
@ -414,9 +385,7 @@ def cut(value, arg):
@register.filter("escape", is_safe=True)
@stringfilter
def escape_filter(value):
"""
Marks the value as a string that should be auto-escaped.
"""
"""Mark the value as a string that should be auto-escaped."""
return conditional_escape(value)
@ -424,7 +393,7 @@ def escape_filter(value):
@stringfilter
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
possible escaping).
"""
@ -435,7 +404,7 @@ def force_escape(value):
@stringfilter
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
followed by a blank line becomes a paragraph break (``</p>``).
"""
@ -447,7 +416,7 @@ def linebreaks_filter(value, autoescape=True):
@stringfilter
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 />``).
"""
autoescape = autoescape and not isinstance(value, SafeData)
@ -460,17 +429,15 @@ def linebreaksbr(value, autoescape=True):
@register.filter(is_safe=True)
@stringfilter
def safe(value):
"""
Marks the value as a string that should not be auto-escaped.
"""
"""Mark the value as a string that should not be auto-escaped."""
return mark_safe(value)
@register.filter(is_safe=True)
def safeseq(value):
"""
A "safe" filter for sequences. Marks each element in the sequence,
individually, as safe, after converting them to strings. Returns a list
A "safe" filter for sequences. Mark each element in the sequence,
individually, as safe, after converting them to strings. Return a list
with the results.
"""
return [mark_safe(str(obj)) for obj in value]
@ -479,7 +446,7 @@ def safeseq(value):
@register.filter(is_safe=True)
@stringfilter
def striptags(value):
"""Strips all [X]HTML tags."""
"""Strip all [X]HTML tags."""
return strip_tags(value)
@ -516,7 +483,7 @@ def _property_resolver(arg):
@register.filter(is_safe=False)
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.
"""
try:
@ -528,7 +495,7 @@ def dictsort(value, arg):
@register.filter(is_safe=False)
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.
"""
try:
@ -539,7 +506,7 @@ def dictsortreversed(value, arg):
@register.filter(is_safe=False)
def first(value):
"""Returns the first item in a list."""
"""Return the first item in a list."""
try:
return value[0]
except IndexError:
@ -548,9 +515,7 @@ def first(value):
@register.filter(is_safe=True, needs_autoescape=True)
def join(value, arg, autoescape=True):
"""
Joins a list with a string, like Python's ``str.join(list)``.
"""
"""Join a list with a string, like Python's ``str.join(list)``."""
if autoescape:
value = [conditional_escape(v) for v in value]
try:
@ -562,7 +527,7 @@ def join(value, arg, autoescape=True):
@register.filter(is_safe=True)
def last(value):
"Returns the last item in a list"
"""Return the last item in a list."""
try:
return value[-1]
except IndexError:
@ -571,7 +536,7 @@ def last(value):
@register.filter(is_safe=False)
def length(value):
"""Returns the length of the value - useful for lists."""
"""Return the length of the value - useful for lists."""
try:
return len(value)
except (ValueError, TypeError):
@ -580,7 +545,7 @@ def length(value):
@register.filter(is_safe=False)
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:
return len(value) == int(arg)
except (ValueError, TypeError):
@ -589,18 +554,14 @@ def length_is(value, arg):
@register.filter(is_safe=True)
def random(value):
"""Returns a random item from the list."""
"""Return a random item from the list."""
return random_module.choice(value)
@register.filter("slice", is_safe=True)
def slice_filter(value, arg):
"""
Returns a slice of the list.
Uses the same syntax as Python's list slicing; see
http://www.diveintopython3.net/native-datatypes.html#slicinglists
for an introduction.
Return a slice of the list using the same syntax as Python's list slicing.
"""
try:
bits = []
@ -618,12 +579,12 @@ def slice_filter(value, arg):
@register.filter(is_safe=True, needs_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.
The list is assumed to be in the proper format. For example, if ``var``
contains: ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``,
then ``{{ var|unordered_list }}`` would return::
Assume the list is in the proper format. For example, if ``var`` contains:
``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then
``{{ var|unordered_list }}`` returns::
<li>States
<ul>
@ -688,7 +649,7 @@ def unordered_list(value, autoescape=True):
@register.filter(is_safe=False)
def add(value, arg):
"""Adds the arg to the value."""
"""Add the arg to the value."""
try:
return int(value) + int(arg)
except (ValueError, TypeError):
@ -701,8 +662,8 @@ def add(value, arg):
@register.filter(is_safe=False)
def get_digit(value, arg):
"""
Given a whole number, returns the requested digit of it, where 1 is the
right-most digit, 2 is the second-right-most digit, etc. Returns 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. Return the
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.
"""
@ -725,7 +686,7 @@ def get_digit(value, arg):
@register.filter(expects_localtime=True, is_safe=False)
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, ''):
return ''
try:
@ -739,7 +700,7 @@ def date(value, arg=None):
@register.filter(expects_localtime=True, is_safe=False)
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, ''):
return ''
try:
@ -753,7 +714,7 @@ def time(value, arg=None):
@register.filter("timesince", is_safe=False)
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:
return ''
try:
@ -766,7 +727,7 @@ def timesince_filter(value, arg=None):
@register.filter("timeuntil", is_safe=False)
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:
return ''
try:
@ -795,15 +756,15 @@ def default_if_none(value, arg):
@register.filter(is_safe=False)
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
@register.filter(is_safe=False)
def yesno(value, arg=None):
"""
Given a string mapping values for true, false and (optionally) None,
returns one of those strings according to the value:
Given a string mapping values for true, false, and (optionally) None,
return one of those strings according to the value:
========== ====================== ==================================
Value Argument Outputs
@ -839,7 +800,7 @@ def yesno(value, arg=None):
@register.filter(is_safe=True)
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.).
"""
try:
@ -882,26 +843,25 @@ def filesizeformat(bytes_):
@register.filter(is_safe=False)
def pluralize(value, arg='s'):
"""
Returns a plural suffix if the value is not 1. By default, 's' is used as
the suffix:
Return a plural suffix if the value is not 1. By default, use 's' as the
suffix:
* If value is 0, vote{{ value|pluralize }} displays "0 votes".
* If value is 1, vote{{ value|pluralize }} displays "1 vote".
* If value is 2, vote{{ value|pluralize }} displays "2 votes".
* If value is 0, vote{{ value|pluralize }} display "0 votes".
* If value is 1, vote{{ value|pluralize }} display "1 vote".
* 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 1, class{{ value|pluralize:"es" }} displays "1 class".
* If value is 2, class{{ value|pluralize:"es" }} displays "2 classes".
* If value is 0, class{{ value|pluralize:"es" }} display "0 classes".
* If value is 1, class{{ value|pluralize:"es" }} display "1 class".
* If value is 2, class{{ value|pluralize:"es" }} display "2 classes".
If the provided argument contains a comma, the text before the comma is
used for the singular case and the text after the comma is used for the
plural case:
If the provided argument contains a comma, use the text before the comma
for the singular case and the text after the comma for the plural case:
* If value is 0, cand{{ value|pluralize:"y,ies" }} displays "0 candies".
* If value is 1, cand{{ value|pluralize:"y,ies" }} displays "1 candy".
* If value is 2, cand{{ value|pluralize:"y,ies" }} displays "2 candies".
* If value is 0, cand{{ value|pluralize:"y,ies" }} display "0 candies".
* If value is 1, cand{{ value|pluralize:"y,ies" }} display "1 candy".
* If value is 2, cand{{ value|pluralize:"y,ies" }} display "2 candies".
"""
if ',' not in arg:
arg = ',' + arg
@ -926,7 +886,7 @@ def pluralize(value, arg='s'):
@register.filter("phone2numeric", is_safe=True)
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)

View File

@ -27,7 +27,7 @@ register = Library()
class AutoEscapeControlNode(Node):
"""Implements the actions of the autoescape tag."""
"""Implement the actions of the autoescape tag."""
def __init__(self, setting, nodelist):
self.setting, self.nodelist = setting, nodelist
@ -542,7 +542,7 @@ def autoescape(parser, token):
@register.tag
def comment(parser, token):
"""
Ignores everything between ``{% comment %}`` and ``{% endcomment %}``.
Ignore everything between ``{% comment %}`` and ``{% endcomment %}``.
"""
parser.skip_past('endcomment')
return CommentNode()
@ -551,7 +551,7 @@ def comment(parser, token):
@register.tag
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
the loop::
@ -644,7 +644,7 @@ def csrf_token(parser, token):
@register.tag
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.
Sample usage::
@ -659,7 +659,7 @@ def debug(parser, token):
@register.tag('filter')
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
arguments -- just like in variable syntax.
@ -689,9 +689,9 @@ def do_filter(parser, token):
@register.tag
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::
@ -738,7 +738,7 @@ def firstof(parser, token):
@register.tag('for')
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``::
@ -847,7 +847,7 @@ def do_ifequal(parser, token, negate):
@register.tag
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::
@ -867,7 +867,7 @@ def ifequal(parser, token):
@register.tag
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.
"""
return do_ifequal(parser, token, True)
@ -899,9 +899,8 @@ class TemplateIfParser(IfParser):
@register.tag('if')
def do_if(parser, token):
"""
The ``{% if %}`` tag evaluates a variable, and if that variable is "true"
(i.e., exists, is not empty, and is not a false boolean value), the
contents of the block are output:
Evaluate a variable, and if that variable is "true" (i.e., exists, is not
empty, and is not a false boolean value), output the contents of the block:
::
@ -916,9 +915,9 @@ def do_if(parser, token):
In the above, if ``athlete_list`` is not empty, the number of athletes will
be displayed by the ``{{ athlete_list|count }}`` variable.
As you can see, the ``if`` tag may take one or several `` {% elif %}``
clauses, as well as an ``{% else %}`` clause that will be displayed if all
previous conditions fail. These clauses are optional.
The ``if`` tag may take one or several `` {% elif %}`` clauses, as well as
an ``{% else %}`` clause that will be displayed if all previous conditions
fail. These clauses are optional.
``if`` tags may use ``or``, ``and`` or ``not`` to test a number of
variables or to negate a given variable::
@ -987,12 +986,12 @@ def do_if(parser, token):
@register.tag
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
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
list of days, only displaying the month if it changes::
@ -1062,7 +1061,7 @@ def load_from_library(library, label, names):
@register.tag
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
``django/templatetags/news/photos.py``::
@ -1093,7 +1092,7 @@ def load(parser, token):
@register.tag
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::
@ -1110,10 +1109,10 @@ def lorem(parser, token):
Examples:
* ``{% lorem %}`` will output the common "lorem ipsum" paragraph
* ``{% lorem 3 p %}`` will output the common "lorem ipsum" paragraph
* ``{% lorem %}`` outputs the common "lorem ipsum" paragraph
* ``{% lorem 3 p %}`` outputs the common "lorem ipsum" paragraph
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())
tagname = bits[0]
@ -1140,9 +1139,9 @@ def lorem(parser, token):
@register.tag
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.
Sample usage::
@ -1163,7 +1162,7 @@ def now(parser, token):
@register.tag
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
``musicians`` is a list of ``Musician`` objects that have ``name`` and
@ -1232,10 +1231,10 @@ def regroup(parser, token):
@register.tag
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
matches the argument, else resets the last rendered cycle tag (named or
If an argument is given, reset the last rendered cycle tag whose name
matches the argument, else reset the last rendered cycle tag (named or
unnamed).
"""
args = token.split_contents()
@ -1258,7 +1257,7 @@ def resetcycle(parser, token):
@register.tag
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::
@ -1268,12 +1267,12 @@ def spaceless(parser, token):
</p>
{% endspaceless %}
This example would return this HTML::
This example returns this HTML::
<p><a href="foo/">Foo</a></p>
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 %}
<strong>
@ -1289,7 +1288,7 @@ def spaceless(parser, token):
@register.tag
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
the bits used in template tags, you must use the ``{% templatetag %}`` tag.
@ -1392,7 +1391,7 @@ def url(parser, token):
@register.tag
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::
@ -1415,8 +1414,8 @@ def verbatim(parser, token):
@register.tag
def widthratio(parser, token):
"""
For creating bar charts and such, this tag calculates the ratio of a given
value to a maximum value, and then applies that ratio to a constant.
For creating bar charts and such. Calculate the ratio of a given value to a
maximum value, and then apply that ratio to a constant.
For example::
@ -1453,7 +1452,7 @@ def widthratio(parser, token):
@register.tag('with')
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.
For example::

View File

@ -56,9 +56,9 @@ class Engine:
@functools.lru_cache()
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
globally available, implicitly configured engine such as:
@ -140,14 +140,14 @@ class Engine:
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.
"""
return Template(template_code, engine=self)
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.
"""
template, origin = self.find_template(template_name)
@ -174,7 +174,7 @@ class Engine:
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:
raise TemplateDoesNotExist("No template names provided")

View File

@ -8,8 +8,7 @@ here.
class TemplateDoesNotExist(Exception):
"""
The exception used when a template does not exist. Accepts the following
optional arguments:
The exception used when a template does not exist. Optional arguments:
backend
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):
"""
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 = []
engines = _engine_list(using)
@ -21,11 +21,11 @@ def get_template(template_name, 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):
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):
"""
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.
"""

View File

@ -295,7 +295,7 @@ def do_extends(parser, token):
@register.tag('include')
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.
Example::

View File

@ -8,10 +8,10 @@ class Loader:
def get_template(self, template_name, skip=None):
"""
Calls self.get_template_sources() and returns a Template object for
the first template matching template_name. If skip is provided,
template origins in skip are ignored. This is used to avoid recursion
during template extending.
Call self.get_template_sources() and return a Template object for
the first template matching template_name. If skip is provided, ignore
template origins in skip. This is used to avoid recursion during
template extending.
"""
tried = []
@ -43,7 +43,7 @@ class Loader:
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).
"""
pass

View File

@ -58,7 +58,7 @@ class SimpleTemplateResponse(HttpResponse):
return obj_dict
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)):
return select_template(template, using=self.using)
elif isinstance(template, str):
@ -71,7 +71,7 @@ class SimpleTemplateResponse(HttpResponse):
@property
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.
This *does not* set the final content of the response. To set the
@ -84,7 +84,7 @@ class SimpleTemplateResponse(HttpResponse):
return content
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,
invoke the callback immediately.
@ -95,11 +95,11 @@ class SimpleTemplateResponse(HttpResponse):
self._post_render_callbacks.append(callback)
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.
Returns the baked response instance.
Return the baked response instance.
"""
retval = self
if not self._is_rendered:
@ -131,8 +131,7 @@ class SimpleTemplateResponse(HttpResponse):
@content.setter
def content(self, value):
"""Sets the content for the response
"""
"""Set the content for the response."""
HttpResponse.content.fset(self, value)
self._is_rendered = True

View File

@ -31,7 +31,7 @@ class TokenBase:
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
@ -42,8 +42,8 @@ class TokenBase:
def infix(bp, func):
"""
Creates an infix operator, given a binding power and a function that
evaluates the node
Create an infix operator, given a binding power and a function that
evaluates the node.
"""
class Operator(TokenBase):
lbp = bp
@ -67,7 +67,7 @@ def infix(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.
"""
class Operator(TokenBase):

View File

@ -7,7 +7,7 @@ register = Library()
@register.filter(is_safe=False)
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``.
"""
return str(formats.localize(value, use_l10n=True))
@ -16,7 +16,7 @@ def localize(value):
@register.filter(is_safe=False)
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``.
"""
return str(value)
@ -41,7 +41,7 @@ class LocalizeNode(Node):
@register.tag('localize')
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`.
Sample usage::

View File

@ -57,7 +57,7 @@ class PrefixNode(template.Node):
@register.tag
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``.
Usage::
@ -75,7 +75,7 @@ def get_static_prefix(parser, token):
@register.tag
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``.
Usage::
@ -143,7 +143,7 @@ class StaticNode(template.Node):
@register.tag('static')
def do_static(parser, token):
"""
Joins the given path with the STATIC_URL setting.
Join the given path with the STATIC_URL setting.
Usage::

View File

@ -19,7 +19,7 @@ class datetimeobject(datetime):
@register.filter
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.
"""
@ -29,7 +29,7 @@ def localtime(value):
@register.filter
def utc(value):
"""
Converts a datetime to UTC.
Convert a datetime to UTC.
"""
return do_timezone(value, timezone.utc)
@ -37,7 +37,7 @@ def utc(value):
@register.filter('timezone')
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.
@ -125,7 +125,7 @@ class GetCurrentTimezoneNode(Node):
@register.tag('localtime')
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``.
Sample usage::
@ -148,7 +148,7 @@ def localtime_tag(parser, token):
@register.tag('timezone')
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
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")
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::