def bitfield_property(fieldname, nbits, doc=None):
    """
    Builder for bitfield properties.

    Bitfield properties are normal Python properties that take values of either
    None, or an integer with a certain number of bits.

    Arguments
    ---------
    nbits : int
        The bitfield size.

    Returns
    -------
    property
        A property that does limit checking to ensure the set value is between
        0 and 2**nbits - 1 (or None).  If the set value lies outside that
        range, it raises a ValueError.

    """
    def setter(self, val):
        # This function is used as a property with its docstring explicitly set
        # in its constructor.
        # pylint: disable=missing-docstring
        if val is None:
            setattr(self, fieldname, val)
        else:
            val = int(val)
            ulim = 2**nbits
            if 0 <= val < ulim:
                setattr(self, fieldname, val)
            else:
                raise ValueError('Value must be less than {}'.format(ulim))

    def getter(self):
        # This function is used as a property with its docstring explicitly set
        # in its constructor.
        # pylint: disable=missing-docstring
        return getattr(self, fieldname)

    return property(getter, setter, doc=doc)