def to_type(value, data_type):
    """Return ``value`` if instance of ``data_type`` else raise error.

    >>> to_type(1, int)
    1
    >>> eggs = to_type("eggs", unicode)
    >>> eggs == "eggs"
    True
    >>> type(eggs) == unicode
    True
    >>> to_type("1+j", complex)
    (1+1j)
    >>> to_type("eggs", float) # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
    Traceback (most recent call last):
        ....
    ValueError: eggs cannot be cast to float.

    """
    if isinstance(value, data_type) or value is None:
        return value
    else:
        try:
            return data_type(value)
        except:
            raise ValueError('%s cannot be cast to %s.' % (value, data_type
                .__name__))
