Dicts

TODO intro

set() Policy

TODO strict, duck, etc.

Validation

If descent_validators is defined, these validators will be run first, before member elements are validated.

If validators is defined, these validators will be run after member elements are validated.

Schema Constructors

classmethod Dict.named(name)

Return a class with name = name

Parameter:name – a string or None. str will be converted to unicode.
Returns:a new class
classmethod Dict.of(*fields)
TODO: doc of()
classmethod Dict.using(**overrides)

Return a class with attributes set from **overrides.

Parameter:**overrides – new values for any attributes already present on the class. A TypeError is raised for unknown attributes.
Returns:a new class

Factory Methods

classmethod Dict.from_object(obj, include=None, omit=None, rename=None, **kw)

Return an element initialized with an object’s attributes.

Parameters:
  • obj – any object
  • include – optional, an iterable of attribute names to pull from obj, if present on the object. Only these attributes will be included.
  • omit – optional, an iterable of attribute names to ignore on obj. All other attributes matching a named field on the Form will be included.
  • rename – optional, a mapping of attribute-to-field name transformations. Attributes specified in the mapping will be included regardless of include or omit.
  • **kw – keyword arguments will be passed to the element’s constructor.

include and omit are mutually exclusive.

This is a convenience constructor for set_by_object():

element = cls(**kw)
element.set_by_object(obj, include, omit, rename)

Configurable Attributes

Mapping.field_schema
TODO: doc field_schema
Dict.policy

One of ‘strict’, ‘subset’ or ‘duck’. Default ‘subset’.

See set() Policy

Dict

class Dict(value=Unspecified, **kw)

Bases: flatland.schema.containers.Mapping, dict

A mapping Container with named members.

add_error(message)
Register an error message on this element, ignoring duplicates.
add_warning(message)
Register a warning message on this element, ignoring duplicates.
clear()
D.clear() -> None. Remove all items from D.
classmethod descent_validated_by(*validators)

Return a class with descent validators set to *validators.

Parameter:*validators – one or more validator functions, replacing any descent validators present on the class.
Returns:a new class
el(path, sep=u'.')

Find a child element by string path.

Parameters:
  • path – a sep-separated string of element names, or an iterable of names
  • sep – optional, a string separator used to parse path
Returns:

an Element or raises KeyError.

>>> first_address = form.el('contact.addresses.0')
>>> first_address.el('street1')
<String u'street1'; value=None>

Given a relative path as above, el() searches for a matching path among the element’s children.

If path begins with sep, the path is considered fully qualified and the search is resolved from the Element.root. The leading sep will always match the root node, regardless of its name.

>>> form.el('.contact.addresses.0.city')
<String u'city'; value=None>
>>> first_address.el('.contact.addresses.0.city')
<String u'city'; value=None>
find(path, single=False, strict=True)

Find child elements by string path.

Parameters:
  • path – a /-separated string specifying elements to select, such as ‘child/grandchild/greatgrandchild’. Relative & absolute paths are supported, as well as container expansion. See Path Lookups.
  • single – if true, return a scalar result rather than a list of elements. If no elements match path, None is returned. If multiple elements match, a LookupError is raised. If multiple elements are found and strict is false, an unspecified element from the result set is returned.
  • strict – defaults to True. If path specifies children or sequence indexes that do not exist, a :ref:`LookupError is raised.
Returns:

a list of Element instances, an Element if single is true, or raises LookupError.

>>> cities = form.find('/contact/addresses[:]/city')
>>> [el.value for el in cities]
[u'Kingsport', u'Dunwich']
>>> form.find('/contact/name', single=True)
<String u'name'; value=u'Obed Marsh'>
flatten(sep=u'_', value=<operator.attrgetter object at 0x16cdd30>)

Export an element hierarchy as a flat sequence of key, value pairs.

Parameters:
  • sep – a string, will join together element names.
  • value – a 1-arg callable called once for each element. Defaults to a callable that returns the u of each element.

Encodes the element hierarchy in a sep-separated name string, paired with any representation of the element you like. The default is the Unicode value of the element, and the output of the default flatten() can be round-tripped with set_flat().

Given a simple form with a string field and a nested dictionary:

>>> from flatland import Dict, String
>>> class Nested(Form):
...     contact = Dict.of(String.named(u'name'),
...                       Dict.named(u'address').          ...                            of(String.named(u'email')))
...
>>> element = Nested()
>>> element.flatten()
[(u'contact_name', u''), (u'contact_address_email', u'')]

The value of each pair can be customized with the value callable:

>>> element.flatten(value=operator.attrgetter('u'))
[(u'contact_name', u''), (u'contact_address_email', u'')]
>>> element.flatten(value=lambda el: el.value)
[(u'contact_name', None), (u'contact_address_email', None)]

Solo elements will return a sequence containing a single pair:

>>> element['name'].flatten()
[(u'contact_name', u'')]
flattened_name(sep=u'_')

Return the element’s complete flattened name as a string.

Joins this element’s path with sep and returns the fully qualified, flattened name. Encodes all Container and other structures into a single string.

Example:

>>> import flatland
>>> form = flatland.List('addresses',
...                      flatland.String('address'))
>>> element = form()
>>> element.set([u'uptown', u'downtown'])
>>> element.el('0').value
u'uptown'
>>> element.el('0').flattened_name()
u'addresses_0_address'
fq_name(sep=u'.')

Return the fully qualified path name of the element.

Returns a sep-separated string of el() compatible element indexes starting from the Element.root (.) down to the element.

>>> from flatland import Dict, Integer
>>> Point = Dict.named(u'point').of(Integer.named(u'x'),
...                                 Integer.named(u'y'))
>>> p = Point(dict(x=10, y=20))
>>> p.name
u'point'
>>> p.fq_name()
u'.'
>>> p['x'].name
u'x'
>>> p['x'].fq_name()
u'.x'

The index used in a path may not be the name of the element. For example, sequence members are referenced by their numeric index.

>>> from flatland import List, String
>>> Addresses = List.named('addresses').of(String.named('address'))
>>> form = Addresses([u'uptown', u'downtown'])
>>> form.name
u'addresses'
>>> form.fq_name()
u'.'
>>> form[0].name
u'address'
>>> form[0].fq_name()
u'.0'
get(key, default=None)
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
classmethod including_descent_validators(*validators, **kw)

Return a class with additional descent *validators.

Parameters:
  • *validators – one or more validator functions
  • position – defaults to -1. By default, additional validators are placed after existing descent validators. Use 0 for before, or any other list index to splice in validators at that point.
Returns:

a new class

classmethod including_validators(*validators, **kw)

Return a class with additional *validators.

Parameters:
  • *validators – one or more validator functions
  • position – defaults to -1. By default, additional validators are placed after existing validators. Use 0 for before, or any other list index to splice in validators at that point.
Returns:

a new class

may_contain(key)
Return True if the element schema allows a field named key.
pop(key)
D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised
popitem()
D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty.
set(value, policy=None)
TODO: doc set()
set_by_object(obj, include=None, omit=None, rename=None)

Set fields with an object’s attributes.

Parameters:
  • obj – any object
  • include – optional, an iterable of attribute names to pull from obj, if present on the object. Only these attributes will be included.
  • omit – optional, an iterable of attribute names to ignore on obj. All other attributes matching a named field on the Form will be included.
  • rename – optional, a mapping of attribute-to-field name transformations. Attributes specified in the mapping will be included regardless of include or omit.

include and omit are mutually exclusive.

Sets fields on self, using as many attributes as possible from obj. Object attributes that do not correspond to field names are ignored.

Mapping instances have two corresponding methods useful for round-tripping values in and out of your domain objects.

update_object() performs the inverse of set_object(), and slice() is useful for constructing new objects.

>>> user = User('biff', 'secret')
>>> form = UserForm()
>>> form.set_by_object(user)
>>> form['login'].value
u'biff'
>>> form['password'] = u'new-password'
>>> form.update_object(user, omit=['verify_password'])
>>> user.password
u'new-password'
>>> user_keywords = form.slice(omit=['verify_password'], key=str)
>>> sorted(user_keywords.keys())
['login', 'password']
>>> new_user = User(**user_keywords)
set_default()
set() the element to the schema default.
set_flat(pairs, sep=u'_')

Set element values from pairs, expanding the element tree as needed.

Given a sequence of name/value tuples or a dict, build out a structured tree of value elements.

setdefault(key, default=None)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
slice(include=None, omit=None, rename=None, key=None)
Return a dict containing a subset of the element’s values.
update(*dictish, **kwargs)
Update with keys from dict-like *dictish and **kwargs
update_object(obj, include=None, omit=None, rename=None, key=<type 'str'>)

Update an object’s attributes using the element’s values.

Produces a slice() using include, omit, rename and key, and sets the selected attributes on obj using setattr.

Returns:nothing. obj is modified directly.
validate(state=None, recurse=True)

Assess the validity of this element and its children.

Parameters:
  • state – optional, will be passed unchanged to all validator callables.
  • recurse – if False, do not validate children. :returns: True or False

Iterates through this element and all of its children, invoking each element’s schema.validate_element(). Each element will be visited twice: once heading down the tree, breadth-first, and again heading back up in reverse order.

Returns True if all validations pass, False if one or more fail.

validate_element(element, state, descending)

Validates on the first (downward) and second (upward) pass.

If descent_validators are defined on the schema, they will be evaluated before children are validated. If a validation function returns flatland.SkipAll or flatland.SkipFalse, downward validation will halt on this container and children will not be validated.

If validators are defined, they will be evaluated after children are validated.

See FieldSchema.validate_element().

classmethod validated_by(*validators)

Return a class with validators set to *validators.

Parameter:*validators – one or more validator functions, replacing any validators present on the class.
Returns:a new class
classmethod with_properties(*iterable, **properties)
TODO: doc
all_children
An iterator of all child elements, breadth-first.
all_valid
True if this element and all children are valid.
copy
D.copy() -> a shallow copy of D
default_value

A calculated “default” value.

If default_factory is present, it will be called with the element as a single positional argument. The result of the call will be returned.

Otherwise, returns default.

When comparing an element’s value to its default value, use this property in the comparison.

has_key
D.has_key(k) -> True if D has a key k, else False
is_empty
Mappings are never empty.
items
D.items() -> list of D’s (key, value) pairs, as 2-tuples
iteritems
D.iteritems() -> an iterator over the (key, value) items of D
iterkeys
D.iterkeys() -> an iterator over the keys of D
itervalues
D.itervalues() -> an iterator over the values of D
keys
D.keys() -> list of D’s keys
parents
An iterator of all parent elements.
path
An iterator of all elements from root to the Element, inclusive.
root
The top-most parent of the element.
u
A string repr of the element.
value
The element as a regular Python dictionary.
values
D.values() -> list of D’s values
x
Sugar, the xml-escaped value of u.
xa
Sugar, the xml-attribute-escaped value of u.

SparseDict

class SparseDict(value=Unspecified, **kw)

Bases: flatland.schema.containers.Dict

A Mapping which may contain a subset of the schema’s allowed keys.

This differs from Dict in that new instances are not created with empty values for all possible keys. In addition, mutating operations are allowed so long as the operations operate within the schema. For example, you may pop() and del members of the mapping.

Configurable Attributes

SparseDict.minimum_fields

The subset of fields to autovivify on instantiation.

May be None or 'required'. If None, mappings will be created empty and mutation operations are unrestricted within the bounds of the field_schema. If required, fields with optional of False will always be present after instantiation, and attempts to remove them from the mapping with del and friends will raise TypeError.