From 4696078832f486ba63f0783a0795294b3d80d862 Mon Sep 17 00:00:00 2001 From: Anton Samarchyan Date: Tue, 24 Jan 2017 15:36:36 -0500 Subject: [PATCH] Refs #27656 -- Updated django.template/tag docstring verbs according to PEP 257. --- django/template/backends/base.py | 16 +- django/template/backends/jinja2.py | 2 +- django/template/base.py | 29 ++-- django/template/context.py | 8 +- django/template/context_processors.py | 6 +- django/template/defaultfilters.py | 216 +++++++++++--------------- django/template/defaulttags.py | 73 +++++---- django/template/engine.py | 10 +- django/template/exceptions.py | 3 +- django/template/loader.py | 12 +- django/template/loader_tags.py | 2 +- django/template/loaders/base.py | 10 +- django/template/response.py | 13 +- django/template/smartif.py | 8 +- django/templatetags/l10n.py | 6 +- django/templatetags/static.py | 6 +- django/templatetags/tz.py | 12 +- 17 files changed, 193 insertions(+), 239 deletions(-) diff --git a/django/template/backends/base.py b/django/template/backends/base.py index ad53089f22..c47c95e51e 100644 --- a/django/template/backends/base.py +++ b/django/template/backends/base.py @@ -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: diff --git a/django/template/backends/jinja2.py b/django/template/backends/jinja2.py index a055f76355..ac7c05895c 100644 --- a/django/template/backends/jinja2.py +++ b/django/template/backends/jinja2.py @@ -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 diff --git a/django/template/base.py b/django/template/base.py index 3946af3802..92ce5c2164 100644 --- a/django/template/base.py +++ b/django/template/base.py @@ -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. + `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. - :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 - 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 {} diff --git a/django/template/context.py b/django/template/context.py index 551a89634c..9f1fcadf72 100644 --- a/django/template/context.py +++ b/django/template/context.py @@ -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): diff --git a/django/template/context_processors.py b/django/template/context_processors.py index 3e73d176ea..56d824f0da 100644 --- a/django/template/context_processors.py +++ b/django/template/context_processors.py @@ -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} diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py index c8e8fb8591..e8e14fd923 100644 --- a/django/template/defaultfilters.py +++ b/django/template/defaultfilters.py @@ -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 (``
``) and a new line followed by a blank line becomes a paragraph break (``

``). """ @@ -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 (``
``). """ 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