Changeset 9689 for main/waeup.kofa


Ignore:
Timestamp:
20 Nov 2012, 00:09:00 (12 years ago)
Author:
uli
Message:

attrs_to_fields now supports an additional 'omit' parameter.

Location:
main/waeup.kofa/trunk/src/waeup/kofa/utils
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • main/waeup.kofa/trunk/src/waeup/kofa/utils/helpers.py

    r9593 r9689  
    384384    return html
    385385
    386 def attrs_to_fields(cls):
     386def attrs_to_fields(cls, omit=[]):
    387387    """Turn the attributes of a class into FieldProperty instances.
    388388
    389389    With Python >= 2.6 we can even use this function as a class decorator.
     390
     391    `omit` is a list of field names that should _not_ be turned into
     392    field properties. This is useful for properties and the like.
    390393    """
    391394    iface = list(implementedBy(cls))[0]
    392395    for field_name in getFieldNames(iface):
     396        if field_name in omit:
     397            continue
    393398        setattr(cls, field_name, FieldProperty(iface[field_name]))
    394399    return cls
  • main/waeup.kofa/trunk/src/waeup/kofa/utils/tests/test_helpers.py

    r9372 r9689  
    2828from cStringIO import StringIO
    2929from zope import schema
    30 from zope.interface import Interface, Attribute, implements
     30from zope.interface import Interface, Attribute, implements, implementer
    3131from zope.security.testing import Principal, Participation
    3232from zope.security.management import newInteraction, endInteraction
     
    5252        self.assertEqual(result4, 30)
    5353        return
     54
     55    def test_attrs_to_fields_properties(self):
     56        # we can omit single fields in order to retrieve properties
     57        class IMyInterface(Interface):
     58            attr1 = schema.Int(
     59                title = u'Attribute 1', readonly = True, default = 110,
     60                )
     61
     62        @helpers.attrs_to_fields
     63        @implementer(IMyInterface)
     64        class MyClass1(object):
     65            @property
     66            def attr1(self):
     67                return 42
     68
     69        @implementer(IMyInterface)
     70        class MyClass2(object):
     71            @property
     72            def attr1(self):
     73                return 42
     74        MyClass2 = helpers.attrs_to_fields(MyClass2, omit=['attr1'])
     75
     76        obj1 = MyClass1()
     77        obj2 = MyClass2()
     78
     79        self.assertEqual(obj1.attr1, 110)
     80        self.assertEqual(obj2.attr1, 42)
     81        return
     82
    5483
    5584class RemoveFileOrDirectoryTestCase(unittest.TestCase):
     
    461490            contents, '\r\n')
    462491        return
     492
    463493
    464494
Note: See TracChangeset for help on using the changeset viewer.