Jinja in Attributes
@check
and @assert
use Jinja syntax to specify the invariants
(properties that should always hold true) of a type.
Checks and Asserts
This example demonstrates @assert and @check on both class fields and the class block itself, and it shows a few examples of Jinja syntax.
this
keyword
Inside a Jinja expression, this
refers to the value of a class field, if the
@assert
or @check
is applied to a class field, and it applies to the whole
object if it is applied to the whole type with @@assert()
or @@check()
.
Filters
In Jinja, functions are called “filters”, and they are applied to arguments
by writing some_argument|some_filter
. Filters can be applied one after the
other by chaining them with additional |
s.
abs
: Absolote value.capitalize
: Make the first letter uppercaseescape
: Replace special HTML characters with their escaped counterpartsfirst
: First item of a listlast
: Last item of a listdefault(x)
: Returnsx
when applied to something undefined.float
: Convert to a float, or 0.0 if conversion failsint
: Convert to an int, or 0 if conversion failsjoin
: Concatenate a list of stringslength
: List lengthlower
: Make the string lowercaseupper
: Make the string uppercasemap(filter)
: Apply a filter to each item in a listmax
: Maximum of a list of numbers or Booleansmin
: Minimum of a list of numbers or Booleansregex_match("regex")
: Return true if argument matches the regexreject("test")
: Filter out items that fail the testreverse
: Reverse a list or stringround
: Round a float to the nearest intselect("test_name")
: Retain the values of a list passingtest_name
sum
: Sum of a list of numberstitle
: Convert a string to “Title Case”trim
: Remove leading and trailing whitespace from a stringunique
: Remove duplicate entries in a list
Common Patterns
Test that a substring appears inside some string
We use the lower
filter to make the whole story lowercase, and pass
the result to regex_match()
to search for an occurrance of “horse”.
Test that a string is an exact match
We can use regex_match
with special control characters indicating
the beginning and end of a string, as in the first @@assert
, or
simply check equality with a literal string as in the second @@assert
.
Test that item prices add up to a total
To check that the numbers in our Receipt
add up, we first
map
over the items to get the price of each item, then sum
the list of prices, and check the sum of the items and the sales
tax against the receipt total.