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
 
* Docs: More improvs to doc strings.
 
* Testing: increase coverage
 
* Rename? class NamedValueAccess+ible:
 
* Benchmarking: Set this up in a new file:
        Testing/BenchNamedValueAccess.py
  so we can experment 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
       
string
sys
types

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

 
class NamedValueAccess
    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 ivars 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
(other than typical things like string and sys).
 
There is no __init__() method and never will be.
 
You can run the test suite by running this module as a program.
 
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 ivars
 
@@ 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:
hasValueForKey(self, key)
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)
resetKeyBindings(self)
setValueForKey(self, key, value)
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>)
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)
valueForName(self, keysString, default=None)
Returns 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)
# Errors
valuesForNames(self, keys, default=None, defaults=None, forgive=0, includeNames=0)
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 is a sequence. default is any kind of object. defaults is a sequence.
  forgive and includeNames is a flag.
If default is not None, then it is substituted when a key is not found.
Otherwise, if defaults is not None, then it's corresponding/parallel value
  for the current key is substituted when a key is not found.
Otherwise, if forgive=1, then unknown keys simply don't produce any values.
Otherwise, if default and defaults are None, and forgive=0, 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

Methods inherited from exceptions.Exception:
__getitem__(...)
__init__(...)
__str__(...)

 
class NamedValueAccessWrapper(NamedValueAccess)
    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:
hasValueForName(self, keysString)
resetKeyBindings(self)
setValueForKey(self, key, value)
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)
valueForUnknownKey(self, key, default)
# Errors
valuesForNames(self, keys, default=None, defaults=None, forgive=0, includeNames=0)
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 is a sequence. default is any kind of object. defaults is a sequence.
  forgive and includeNames is a flag.
If default is not None, then it is substituted when a key is not found.
Otherwise, if defaults is not None, then it's corresponding/parallel value
  for the current key is substituted when a key is not found.
Otherwise, if forgive=1, then unknown keys simply don't produce any values.
Otherwise, if default and defaults are None, and forgive=0, 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

Methods inherited from exceptions.Exception:
__getitem__(...)
__init__(...)
__str__(...)

 
Functions
       
time(...)
time() -> floating point number
 
Return the current time in seconds since the Epoch.
Fractions of a second may be present if the system clock provides them.
valueForKey(obj, key, default=<class MiscUtils.NoDefault>)
Returns 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>)
Returns 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