MiscUtils.NamedValueAccess | index /usr/local/share/webware/MiscUtils/NamedValueAccess.py

`NamedValueAccess provides functions, a mix-in class and a wrapper class
all for accessing Python objects by named attributes. You can use which
ever of the three approaches best suites your needs and style.
NOTES
If Python provided a root class 'Object' in the same tradition as other
OOP languages such as Smalltalk, Objective-C and Java, then we could
dispense with the global functions and simply stick with the mix-in.
TO DO
* The mix-in's valueForKey() could be out of slight alignment with the
function, since they have different implementations. However, the test
cases pass for both right now.
* Should the valueForKey() function provide for caching of bindings in
the same manner than the mix-in does?
If not, should the mix-in allow an option to *not* cache bindings?
* hasValueForKey() function? (We already have a method in the mix-in)
* valuesForNames() in the mix-in:
* Change parameter 'keys' to 'names'
* Use NoDefault instead of None in the parameters
* Revisit doc string and test cases
* Testing: increase coverage
* Rename? class NamedValueAccess+ible:
* Benchmarking: Set this up in a new file:
Tests/BenchNamedValueAccess.py
so we can experiment with caching vs. not and other techniques.
PAST DESIGN DECISIONS
* Only if a name binds to a method is it invoked. Another approach is
to invoke any value that is __call__able, but that is unPythonic: If
obj.foo is a class or a function then obj.foo gives that class or
function, not the result of invoking it. Method is the only
convenience we provide, because that's one of the major points of
providing this.
CREDIT
Chuck Esterbrook <echuck@mindspring.com>
Tavis Rudd <tavis@calrudd.com>`

Modules

``

types |  |  |

Classes

``

NamedValueAccess
  NamedValueAccessWrapper
exceptions.LookupError(exceptions.StandardError)
  NamedValueAccessError
    ValueForKeyError

class NamedValueAccess

``

`Mix-in class for accessing Python objects by named attributes.
This class is intended to be ancestor class such that you can say:
from NamedValueAccess import *
age = someObj.valueForName("age")
name = someObj.valueForName("info.fields.name")
This can be useful in setups where you wish to textually refer to the
objects in a program, such as an HTML template processed in the context
of an object-oriented framework.
Keys can be matched to either methods or instance variables and with
or without underscores.
valueForName() can also traverse bona fide dictionaries (DictType).
You can safely import * from this module.
Only the NamedValueAccess class is exported.
There is no __init__() method and never will be.
You'll see the terms 'key' and 'name' in the class and its documentation.
A 'key' is a single identifier such as 'foo'. A name could be key, or a
qualified key, such as 'foo.bar.boo'. Names are generally more convenient
and powerful, while key-oriented methods are more efficient and provide
the atomic functionality that name-oriented methods are built upon.
From a usage point of view, you normally just use the 'name' methods
and forget about the 'key'.
@@ 2000-05-21 ce: This class causes problems when used in WebKit for logging.
Perhaps circular references?
Involving self?
Having to do with methods bound to their objects?
@@ 2000-03-03 ce: document instance variables
@@ 2000-04-24 ce: Some classes like UserDict need to use getitem()
instead of getattr() and don't need to deal with _bindingForGetKey().
@@ 2000-05-31 ce: Rename this class to NamedValues, NamedValueAccess, ValuesByName
@@ This class probably needs to be in MiscUtils, as it's being used in that
way while MiddleKit was intended for "enterprise/business objects".
`

Methods defined here:

handleUnknownSetKey(self, key)

hasValueForKey(self, key)
  `Check whether key is available.
  Returns true if the key is available, although that does not guarantee
  that there will not be errors caused by retrieving the key.`

hasValueForName(self, keysString)
  `Check whether name is available.`

resetKeyBindings(self)
  `Rest all key bindings, releasing alreaedy referenced values.`

setValueForKey(self, key, value)
  `Set value for a given key.
  Suppose key is 'foo'.
  This method sets the value with the following precedence:
  1. Public attributes before private attributes
  2. Methods before non-methods
  More specifically, this method then uses one of the following:
  @@ 2000-03-04 ce: fill in
  ... or invokes handleUnknownSetKey().`

valueForKey(self, key, default=<class MiscUtils.NoDefault>)
  `Get value for given key.
  Suppose key is 'foo'.
  This method returns the value with the following precedence:
  1. Methods before non-methods
  2. Public attributes before private attributes
  More specifically, this method then returns one of the following:
  * foo()
  * _foo()
  * self.foo
  * self._foo
  ... or default, if it was specified,
  otherwise invokes and returns result of valueForUnknownKey().
  Note that valueForUnknownKey() normally returns an exception.
  See valueForName() which is a more advanced version of this method
  that allows multiple, qualified keys.`

valueForKeySequence(self, listOfKeys, default=None)
  `Get the value for the given list of keys.`

valueForName(self, keysString, default=None)
  `Get the value for the given keysString.
  This is the more advanced version of valueForKey(), which can only
  handle single names. This method can handle
  'foo', 'foo1.foo2', 'a.b.c.d', etc.
  It will traverse dictionaries if needed.`

valueForUnknownKey(self, key, default)

valuesForNames(self, keys, default=None, defaults=None, forgive=0, includeNames=0)
  `Get all values for given names.
  Returns a list of values that match the given keys, each of which is
  passed through valueForName() and so could be of the form 'a.b.c'.
  keys and defaults are sequences.
  default is any kind of object.
  forgive and includeNames are flags.
  If default is not None, then it is substituted when a key is not found.
  Otherwise, if defaults is not None, then its corresponding/parallel
  value for the current key is substituted when a key is not found.
  Otherwise, if forgive is true, then unknown keys simply don't produce
  any values.
  Otherwise, if default and defaults are None, and forgive is false,
  then the unknown keys will probably raise an exception through
  valueForUnknownKey() although that method can always return
  a final, default value.
  if keys is None, then None is returned.
  If keys is an empty list, then None is returned.
  Often these last four arguments are specified by key.
  Examples:
  names = ['origin.x', 'origin.y', 'size.width', 'size.height']
  obj.valuesForNames(names)
  obj.valuesForNames(names, default=0.0)
  obj.valuesForNames(names, defaults=[0.0, 0.0, 100.0, 100.0])
  obj.valuesForNames(names, forgive=0)
  @@ 2000-03-04 ce: includeNames is only supported when forgive=1.
  It should be supported for the other cases.
  It should be documented.
  It should be included in the test cases.`

class NamedValueAccessError(exceptions.LookupError)

``

Method resolution order:
  NamedValueAccessError
  exceptions.LookupError
  exceptions.StandardError
  exceptions.Exception
  exceptions.BaseException
  __builtin__.object

Data descriptors defined here:

__weakref__
  `list of weak references to the object (if defined)`

Methods inherited from exceptions.LookupError:

__init__(...)
  `x.__init__(...) initializes x; see x.__class__.__doc__ for signature`

Data and other attributes inherited from exceptions.LookupError:

__new__ = <built-in method __new__ of type object>
  `T.__new__(S, ...) -> a new object with type S, a subtype of T`

Methods inherited from exceptions.BaseException:

__delattr__(...)
  `x.__delattr__('name') <==> del x.name`

__getattribute__(...)
  `x.__getattribute__('name') <==> x.name`

__getitem__(...)
  `x.__getitem__(y) <==> x[y]`

__getslice__(...)
  `x.__getslice__(i, j) <==> x[i:j]
  Use of negative indices is not supported.`

__reduce__(...)

__repr__(...)
  `x.__repr__() <==> repr(x)`

__setattr__(...)
  `x.__setattr__('name', value) <==> x.name = value`

__setstate__(...)

__str__(...)
  `x.__str__() <==> str(x)`

__unicode__(...)

Data descriptors inherited from exceptions.BaseException:

__dict__

args

message

class NamedValueAccessWrapper(NamedValueAccess)

``

`Mix-in class for accessing Python objects by named attributes.
This provides a wrapper around an existing object which will respond
to the methods of NamedValueAccess. By using the wrapper, you can
stick with objects and methods such as obj.valueForName('x.y') (as
opposed to functions like valueForName()) and refrain from modifying
the existing class hierarchy with NamedValueAccess.
Example:
wrapper = NamedValueAccessWrapper(obj)
print wrapper.valueForName('manager.name')
`

Methods defined here:

__init__(self, object)

hasValueForKey(self, key)

valueForKey(self, key, default=<class MiscUtils.NoDefault>)

valueForName(self, key, default=<class MiscUtils.NoDefault>)

Methods inherited from NamedValueAccess:

handleUnknownSetKey(self, key)

hasValueForName(self, keysString)
  `Check whether name is available.`

resetKeyBindings(self)
  `Rest all key bindings, releasing alreaedy referenced values.`

setValueForKey(self, key, value)
  `Set value for a given key.
  Suppose key is 'foo'.
  This method sets the value with the following precedence:
  1. Public attributes before private attributes
  2. Methods before non-methods
  More specifically, this method then uses one of the following:
  @@ 2000-03-04 ce: fill in
  ... or invokes handleUnknownSetKey().`

valueForKeySequence(self, listOfKeys, default=None)
  `Get the value for the given list of keys.`

valueForUnknownKey(self, key, default)

valuesForNames(self, keys, default=None, defaults=None, forgive=0, includeNames=0)
  `Get all values for given names.
  Returns a list of values that match the given keys, each of which is
  passed through valueForName() and so could be of the form 'a.b.c'.
  keys and defaults are sequences.
  default is any kind of object.
  forgive and includeNames are flags.
  If default is not None, then it is substituted when a key is not found.
  Otherwise, if defaults is not None, then its corresponding/parallel
  value for the current key is substituted when a key is not found.
  Otherwise, if forgive is true, then unknown keys simply don't produce
  any values.
  Otherwise, if default and defaults are None, and forgive is false,
  then the unknown keys will probably raise an exception through
  valueForUnknownKey() although that method can always return
  a final, default value.
  if keys is None, then None is returned.
  If keys is an empty list, then None is returned.
  Often these last four arguments are specified by key.
  Examples:
  names = ['origin.x', 'origin.y', 'size.width', 'size.height']
  obj.valuesForNames(names)
  obj.valuesForNames(names, default=0.0)
  obj.valuesForNames(names, defaults=[0.0, 0.0, 100.0, 100.0])
  obj.valuesForNames(names, forgive=0)
  @@ 2000-03-04 ce: includeNames is only supported when forgive=1.
  It should be supported for the other cases.
  It should be documented.
  It should be included in the test cases.`

class ValueForKeyError(NamedValueAccessError)

``

Method resolution order:
  ValueForKeyError
  NamedValueAccessError
  exceptions.LookupError
  exceptions.StandardError
  exceptions.Exception
  exceptions.BaseException
  __builtin__.object

Data descriptors inherited from NamedValueAccessError:

__weakref__
  `list of weak references to the object (if defined)`

Methods inherited from exceptions.LookupError:

__init__(...)
  `x.__init__(...) initializes x; see x.__class__.__doc__ for signature`

Data and other attributes inherited from exceptions.LookupError:

__new__ = <built-in method __new__ of type object>
  `T.__new__(S, ...) -> a new object with type S, a subtype of T`

Methods inherited from exceptions.BaseException:

__delattr__(...)
  `x.__delattr__('name') <==> del x.name`

__getattribute__(...)
  `x.__getattribute__('name') <==> x.name`

__getitem__(...)
  `x.__getitem__(y) <==> x[y]`

__getslice__(...)
  `x.__getslice__(i, j) <==> x[i:j]
  Use of negative indices is not supported.`

__reduce__(...)

__repr__(...)
  `x.__repr__() <==> repr(x)`

__setattr__(...)
  `x.__setattr__('name', value) <==> x.name = value`

__setstate__(...)

__str__(...)
  `x.__str__() <==> str(x)`

__unicode__(...)

Data descriptors inherited from exceptions.BaseException:

__dict__

args

message

Functions

``

valueForKey(obj, key, default=<class MiscUtils.NoDefault>)
  `Get the value of the object named by the given key.
  Suppose key is 'foo'.
  This method returns the value with the following precedence:
  1. Methods before non-methods
  2. Attributes before keys (__getitem__)
  3. Public things before private things
  (private being denoted by a preceding underscore)
  More specifically, this method returns one of the following:
  * obj.valueForKey(key) # only if the method exists
  * obj.foo()
  * obj._foo()
  * obj.foo
  * obj._foo
  * obj['foo']
  * obj.valueForUnknownKey(key)
  * default # only if specified
  If all of these fail, a ValueForKeyError is raised.
  NOTES
  * If the object provides a valueForKey() method, that method will be
  invoked to do the work.
  * valueForKey() works on dictionaries and dictionary-like objects.
  * valueForUnknownKey() provides a hook by which objects can
  delegate or chain their keyed value access to other objects.
  The key and default arguments are passed to it and it should
  generally respect the typical treatment of the the default
  argument as found throughout Webware and described in the Style
  Guidelines.
  * See valueForName() which is a more advanced version of this
  function that allows multiple, qualified keys.`

valueForName(obj, name, default=<class MiscUtils.NoDefault>)
  `Get the value of the object that is named.
  The name can use dotted notation to traverse through a network/graph
  of objects. Since this function relies on valueForKey() for each
  individual component of the name, you should be familiar with the
  semantics of that notation.
  Example: valueForName(obj, 'department.manager.salary')`

Data
`` |  | technique = 1