Next topic

mmf.physics

This Page

mmf.objects.attributes

argsfrom(Class[, exclude])

Module to facilitate attribute definition.

Goal:

To provide a method for easily specifying the _state_vars of classes and the arguments of functions. This should allow: - Easy specification of _state_vars, including

  • default values and
  • documentation.
  • Incoporation of specification in docstrings.
  • Automatic definition of __init__ to provide construction and copy-construction based on parameter specification.
  • Automatic construction of archiving, persistence (pickling), and repr/str.
  • Easy techniques for combining objects, either through - inheritance or - delegation.

For functions, support should be provided so that the arguments can be easily specified and constructed. - Easy specification of arguments, including

  • documentation and
  • defaults.
  • Automatic generation of argument processing.
  • Easy technique for combining arguments from delegates.
  • Automatic checking of argument.
Strategy:
  • For classes, define a metaclass to generate the documentation etc. Desired functionality is provided through inheritance.
  • For functions, use decorator syntax.

Example:

>>> import mmf.objects
>>> class Complex(mmf.objects.StateVars):
...     _state_vars = [('x', 0.0, 'Real part'),
...                    ('y', 0.0, 'Imaginary part')]
...     mmf.objects.process_vars()
>>> z1 = Complex()
>>> z1
Complex()
>>> z2 = Complex(x=1.0, y=2.0)
>>> z2
Complex(x=1.0, y=2.0)
>>> z3 = Complex(z2)
>>> z3
Complex(x=1.0, y=2.0)

>> class Options(mmf.objects.StateVars): ... _state_vars = [(‘tol’, 1e-5, “Tolerance”), ... (‘max_iter’, 1000, “Maximum number of iterations”), ... (‘verbose’, True)] ... mmf.objects.process_vars() >> @argsfrom(Options) ... def sqrt(n, _args): ... “Compute sqrt(n) using Newton’s method” ... opt = Options(_args) ... _args.check_usage() # Check to make sure all args were used. ... x0 = 1.0 ... for i in xrange(opt.max_iter): ... x1 = x0 - (x0*x0-n)/(2.0*x0) ... if abs(x0-x1) < opt.tol: ... return x1 ... x0 = x1 >> sqrt(2) # doctest: +ELLIPSIS 1.41421...

One option which is presently rejected is the following syntax: class Complex(object):

x = attribute(“Real part”, default=0.0) y = attribute(“Imaginary part”, default=0.0)

This reads nicely, but does not preserve the order of attributes. It is desirable to keep the order of attributes so that important attributes can be specified before less important ones.

mmf.objects.attributes.argsfrom(Class, exclude=[])[source]