The lima API

Please note that the lima API uses a relatively uncommon feature of Python 3: Keyword-only arguments.

Keyword-only arguments

Keyword-only arguments can be recognized by their position in a method/function signature: Every argument coming after the varargs argument like *args (or after a single *) is a keyword-only argument.

A function that is defined as def foo(*, x, y): pass must be called like this: foo(x=1, y=2); calling foo(1, 2) will raise a TypeError.

It is the author’s opinion that enforcing keyword arguments in the right places makes the resulting code more readable.

For more information about keyword-only arguments, see PEP 3102

lima.fields

Field classes and related code.

lima.fields.type_mapping =dict(...)

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s

(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
class lima.fields.Boolean(*, attr=None, get=None)

A boolean field.

currently this class has no additional functionality compared to Field. Nevertheless it should be used over Field when referencing boolean values as an indicator for a field’s type and to keep code future-proof.

class lima.fields.Date(*, attr=None, get=None)

A date field.

static pack(val)

Return a string representation of val.

Parameters:val – The datetime.date object to convert.
Returns:The ISO 8601-representation of val (YYYY-MM-DD).
class lima.fields.DateTime(*, attr=None, get=None)

A DateTime field.

static pack(val)

Return a string representation of val.

Parameters:val – The datetime.datetime object to convert.
Returns:The ISO 8601-representation of val (YYYY-MM-DD%HH:MM:SS.mmmmmm+HH:MM for datetime.datetime objects with Timezone information and microsecond precision).
class lima.fields.Field(*, attr=None, get=None)

Base class for fields.

Parameters:
  • attr – The optional name of the corresponding attribute.
  • get – An optional getter function accepting an object as its only parameter and returning the field value.

When a Field has both attr and get defined (either via passing them to the constructor of Field or because the subclass implements attr or get on the class level, get always takes precedence.

If neither get nor attr are defined (not per instance and not at the class level), lima.schema.Schema.dump() tries to get the field value by looking for an attribute of the same name the Field has within the corresponding lima.schema.Schema instance.

class lima.fields.Float(*, attr=None, get=None)

A float field.

currently this class has no additional functionality compared to Field. Nevertheless it should be used over Field when referencing float values as an indicator for a field’s type and to keep code future-proof.

class lima.fields.Integer(*, attr=None, get=None)

An integer field.

currently this class has no additional functionality compared to Field. Nevertheless it should be used over Field when referencing integer values as an indicator for a field’s type and to keep code future-proof.

class lima.fields.Nested(*, schema, attr=None, get=None, **kwargs)

A Field referencing another object with it’s respective schema.

Parameters:
  • schema – The schema of the referenced object. This can be specified via a schema object, a schema class (that will get instantiated immediately) or the qualified name of a schema class (for when the named schema has not been defined at the time of the Nested object’s creation). If two or more schema classes with the same name exist in different modules, the schema class name has to be fully module-qualified (see the entry on class names for clarification of these concepts). Schemas defined within a local namespace can not be referenced by name.
  • attr – The optional name of the corresponding attribute.
  • get – An optional getter function accepting an object as its only parameter and returning the field value.
  • kwargs – Optional keyword arguments to pass to the Schema‘s constructor when the time has come to instance it. Must be empty if schema is a lima.schema.Schema object.
Raises:

ValueError – If kwargs are specified even if schema is a lima.schema.Schema object.

Examples:

# refer to PersonSchema class
author = Nested(schema=PersonSchema)

# refer to PersonSchema class with additional params
artists = Nested(schema=PersonSchema, exclude='email', many=True)

# refer to PersonSchema object
author = Nested(schema=PersonSchema())

# refer to PersonSchema object with additional params
# (note that Nested() gets no kwargs)
artists = Nested(schema=PersonSchema(exclude='email', many=true))

# refer to PersonSchema per name
author = Nested(schema='PersonSchema')

# refer to PersonSchema per name with additional params
author = Nested(schema='PersonSchema', exclude='email', many=True)

# refer to PersonSchema per module-qualified name
# (in case of ambiguity)
author = Nested(schema='project.persons.PersonSchema')

# specify attr name as well
user = Nested(attr='login_user', schema=PersonSchema)
pack(val)

Return the output of the referenced object’s schema’s dump method.

If the referenced object’s schema was specified by name at the Nested field’s creation, this is the time when this schema is instantiated (this is done only once).

Parameters:val – The nested object to convert.
Returns:The output of the referenced lima.schema.Schema‘s lima.schema.Schema.dump() method.
class lima.fields.String(*, attr=None, get=None)

A string field.

currently this class has no additional functionality compared to Field. Nevertheless it should be used over Field when referencing string values as an indicator for a field’s type and to keep code future-proof.

lima.schema

Schema class and related code.

class lima.schema.Schema(*, exclude=None, only=None, many=False)

Base class for Schemas.

Parameters:
  • exclude – A sequence of field names to be removed from the fields of the new Schema instance. If only one field is to be removed, it’s ok to supply a simple string instead of a list containing only one string for exclude. exclude may not be specified together with only.
  • only – A sequence of the names of the only fields that shall remain for the new Schema instance. If just one field is to remain, it’s ok to supply a simple string instead of a list containing only one string for only. only may not be specified together with exclude.
  • many – A boolean indicating if the new Schema will be serializing single objects (many=False) or collections of objects (many=True) per default. This can later be overridden in the dump() Method.

Upon creation, each Schema object gets an internal mapping of field names to fields.

This mapping starts out as a copy of the classes __fields__ attribute. (Note that the fields themselves are not copied - changing a field for a Schema instance changes this field for the class and all base classes as well. This behaviour might change in the future. In general, it’s good practice not to change fields once created.)

The internal mapping and is then modified depending the arguments supplied to the Schema‘s constructor:

For an explanation on how the class’s __fields__ attribute is determined, see SchemaMeta.

Also upon creation, each Schema object gets an individually created dump function that aims to unroll most of the loops and to minimize the number of attribute lookups, resulting in a little speed gain on serialization.

Schema classes defined outside of local namespaces can be referenced by name (used by lima.fields.Nested).

dump(obj, *, many=None)

Return a marshalled representation of obj.

Parameters:
  • obj – The object (or collection of objects) to marshall.
  • many – Wether obj is a single object or a collection of objects. If many is None, the value of the instance’s many attribute is used.
Returns:

A representation of obj in the form of a JSON-serializable dict, with each entry corresponding to one of the Schema‘s fields. (Or a list of such dicts in case a collection of objects was marshalled)

class lima.schema.SchemaMeta

Metaclass of Schema.

Note

The metaclass SchemaMeta is used internally to simplify the configuration of new Schema classes. For users of the library there should be no need to use SchemaMeta directly.

When defining a new Schema (sub)class, SchemaMeta makes sure that the new class has a class attribute __fields__ of type dict containing the fields for the new Schema.

__fields__ is determined like this:

  • The __fields__ dicts of all base classes are copied (with base classes specified first having precedence). (Note that the fields themselves are not copied - changing an inherited field changes this field for all the base classes as well. This behaviour might change in the future. In general, it’s good practice not to change fields once created.)
  • Fields (Class variables of type lima.abc.FieldABC) are moved out of the class dict and into the __fields__ dict.
  • If present, the class attribute __lima_args__ is removed from the class dict and evaluated as follows:
    • Fields specified via an optional dict __lima_args__['include'] are added (overriding any fields of the same name present therein).
    • Fields named in an optional sequence __lima_args__['exclude'] are removed. If only one field is to be removed, it’s ok to supply a simple string instead of a list containing only one string.

SchemaMeta also makes sure the new Schema class is registered with the lima class registry lima.registry (at least if the Schema isn’t defined inside a local namespace, where we wouldn’t find it later on).

lima.exc

The lima exception hierarchy.

Currently this module only holds Exceptions related to lima.registry, but this might change in the future.

exception lima.exc.AmbiguousClassNameError

Raised when asking for a class with an ambiguous name.

Usually this is the case if two or more classes of the same name were registered from within different modules, and afterwards a registry is asked for one of those classes without specifying the module in the class name.

exception lima.exc.ClassNotFoundError

Raised when a class was not found by a registry.

exception lima.exc.RegisterLocalClassError

Raised when trying to register a class defined in a local namespace.

exception lima.exc.RegistryError

The base class for all registry-related exceptions.

lima.abc

Abstract base classes for fields and schemas.

Note

lima.abc is needed to avoid circular imports of fields needing to know about schemas and vice versa. The base classes are used for internal type checks. For users of the library there should be no need to use lima.abc directly.

class lima.abc.FieldABC

Abstract base class for fields.

Inheriting from FieldABC marks a class as a field for internal type checks.

(Usually, it’s a way better Idea to subclass lima.fields.Field directly)

class lima.abc.SchemaABC

Abstract base class for schemas.

Inheriting from SchemaABC marks a class as a schema for internal type checks.

(Usually, it’s a way better Idea to subclass lima.schema.Schema directly)

lima.registry

Module for the Registry class.

Note

A global lima.registry.Registry object is used internally to allow instances of lima.fields.Nested to reference by name lima.schema.Schema classes that have not been defined at the time of referencing. For users of the library there should be no need to use anything within lima.registry directly.

lima.registry.global_registry =lima.registry.Registry()

A class registry.

class lima.registry.Registry

A class registry.

get(name)

Get a registered class by its name and return it.

Parameters:

name – The name of the class to look up. Has to be either the class’s qualified name or the class’s fully module-qualified name in case two classes with the same qualified name from different modules were registered (see the entry on class names for clarification of these concepts). Schemas defined within a local namespace can not be referenced by name.

Returns:

The specified class.

Raises:
register(cls)

Register a class.

Parameters:cls – The class to register. Must not have been defined in a local namespace.
Raises:RegisterLocalClassError – In case cls is a class defined in a local namespace (see exc.RegisterLocalClassError).