Package pyffi :: Package object_models :: Module simple_type
[hide private]
[frames] | no frames]

Source Code for Module pyffi.object_models.simple_type

  1  """Defines the base class for simple types.""" 
  2   
  3  # -------------------------------------------------------------------------- 
  4  # ***** BEGIN LICENSE BLOCK ***** 
  5  # 
  6  # Copyright (c) 2007-2011, Python File Format Interface 
  7  # All rights reserved. 
  8  # 
  9  # Redistribution and use in source and binary forms, with or without 
 10  # modification, are permitted provided that the following conditions 
 11  # are met: 
 12  # 
 13  #    * Redistributions of source code must retain the above copyright 
 14  #      notice, this list of conditions and the following disclaimer. 
 15  # 
 16  #    * Redistributions in binary form must reproduce the above 
 17  #      copyright notice, this list of conditions and the following 
 18  #      disclaimer in the documentation and/or other materials provided 
 19  #      with the distribution. 
 20  # 
 21  #    * Neither the name of the Python File Format Interface 
 22  #      project nor the names of its contributors may be used to endorse 
 23  #      or promote products derived from this software without specific 
 24  #      prior written permission. 
 25  # 
 26  # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
 27  # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
 28  # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
 29  # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
 30  # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
 31  # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
 32  # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 33  # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
 34  # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
 35  # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
 36  # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 37  # POSSIBILITY OF SUCH DAMAGE. 
 38  # 
 39  # ***** END LICENSE BLOCK ***** 
 40  # -------------------------------------------------------------------------- 
 41   
 42  from pyffi.object_models.any_type import AnyType 
43 44 -class _MetaSimpleType(type):
45 """This metaclass binds the get_value and set_value methods to the 46 value property. We need a metaclass for this because properties are 47 non-polymorphic. Further reading: 48 http://stackoverflow.com/questions/237432/python-properties-and-inheritance 49 http://requires-thinking.blogspot.com/2006/03/note-to-self-python-properties-are-non.html 50 """
51 - def __init__(cls, name, bases, dct):
52 # call base class constructor 53 super(_MetaSimpleType, cls).__init__(name, bases, dct) 54 # add value property 55 cls.value = property(cls.get_value, cls.set_value, 56 None, cls.value.__doc__)
57
58 -class SimpleType(AnyType):
59 """Base class from which all simple types are derived. Simple 60 types contain data which is not divided further into smaller pieces, 61 and that can represented efficiently by a (usually native) Python type, 62 typically ``int``, ``float``, or ``str``. 63 64 A brief example of usage: 65 66 >>> class Short(SimpleType): 67 ... def __init__(self): 68 ... # for fun, let default value be 3 69 ... self._value = 3 70 ... def set_value(self, value): 71 ... # check type 72 ... if not isinstance(value, int): 73 ... raise TypeError("Expected int but got %s." 74 ... % value.__class__.__name__) 75 ... # check range 76 ... if value < -0x8000 or value > 0x7fff: 77 ... raise ValueError("Value %i out of range." % value) 78 ... self._value = value 79 >>> test = Short() 80 >>> print(test) 81 3 82 >>> test.value = 255 83 >>> print(test) 84 255 85 >>> test.value = 100000 # doctest: +ELLIPSIS 86 Traceback (most recent call last): 87 ... 88 ValueError: ... 89 >>> test.value = "hello world" # doctest: +ELLIPSIS 90 Traceback (most recent call last): 91 ... 92 TypeError: ... 93 94 Also override :meth:`read` and :meth:`write` if you wish to read and write data 95 of this type, and :meth:`is_interchangeable` if you wish to declare data as 96 equivalent. 97 """ 98 99 __metaclass__ = _MetaSimpleType 100 101 # added here for documentation purposes - actually set in 102 # metaclass 103 @property
104 - def value(self):
105 """A property which wraps the actual data. This property 106 always calls :meth:`set_value` to assign the value, and ensures 107 that the value is valid (type, range, ...). Unless you know 108 what you are doing, always use the `value` property to change 109 the data. 110 """ 111 return None
112 113 _value = None 114 """The data.""" 115
116 - def __str__(self):
117 """String representation. This implementation is simply a wrapper 118 around ``str`` on :attr:`_value`. 119 120 :return: String representation. 121 :rtype: ``str`` 122 """ 123 return self._value.__str__()
124
125 - def get_value(self):
126 """Return the stored value. 127 128 :return: The stored value. 129 :rtype: Whatever is appropriate. 130 """ 131 return self._value
132
133 - def set_value(self, value):
134 """Set stored value. Override this method to enable validation 135 (type checking, range checking, and so on). 136 137 :param value: The value to store. 138 :type value: Whatever is appropriate. 139 """ 140 self._value = value
141 142 # AnyType 143
144 - def is_interchangeable(self, other):
145 """This checks for object identity of the value.""" 146 return isinstance(other, SimpleType) and (self._value is other._value)
147 148 # DetailNode 149
150 - def get_detail_display(self):
151 """Display string for the detail tree. This implementation is simply 152 a wrapper around C{self.:attr:`_value`.__str__()}. 153 154 :return: String representation. 155 :rtype: ``str`` 156 """ 157 return self._value.__str__()
158