Record Container

This module provides a container that combines aspects of dict, tuple and object. It is implemented as a class factory, in a similar way to collections.namedtuple, and has the following features:

  • The constructor can take defaults and type annotations; if type annotations are present they are checked by default.
  • The constructor can used like a tuple, or with named arguments like dict.
  • The generated class subclasses dict and so has the usual dict iteration / read methods.
  • Contents can be accessed via [] and also via attributes (it unifies the __getitem__() and the __getattr__() protocols).
  • Optionally, instances can be read–only (immutable), in which case they are also hashable.
  • Instances are fixed in size, containing only the entries specified in the constructor, unless an additional __ argument is given (which can optionally specify a type for extra values).
pytyp.spec.record.record(typename, field_names, verbose=False, mutable=False, checked=True, context=None)[source]

This creates a wrapper around dict that allows attribute access. In other words: it unifies Rec() and Atr(); it provides both __..item__ and __..attr__ access.

Parameters:
  • typename – The name of the class to be created.
  • field_names – An argument list in normal Python syntax. This can include default values and type annotations. For example: ‘a,b=5’ or ‘a:int,b:Seq(str)’.
  • verbose – (default False) If True the source will be printed to stdout.
  • mutable – (default False) If True contents can be changed; it False the instance can be hashed.
  • checked – (default True) If True, initial arguments and future modifications (if any) are checked against type specifications (if given in field_names).
  • context – (default None) A dict that can provide access to additional names used in field_names. The pytyp.spec.abcs module is always available.

Here are some examples:

>>> MyTuple = record('MyTuple', ',') # no names or types - like a tuple
>>> t = MyTuple(1,2)
>>> t[0]
1
>>> t._1 # attribute access to indexed fields
2
>>> hash(t)
7114083200724408387

>>> Record = record('Record', 'a:str,b:int=7', mutable=True)
>>> r = Record('foo')
>>> r.b
7
>>> r.b = 41
>>> r['a'] = 42
Exception raised:
  ...
TypeError: Type str inconsistent with 42.

>>> Variable = record('Variable', '__:int')
>>> v = Variable(a=1,b=2,c=3)
>>> len(v)
3

This Page