def coerce(P, x):
    """
    Coerce ``x`` to type ``P`` if possible.

    EXAMPLES::

        sage: type(5)
        <type 'sage.rings.integer.Integer'>
        sage: type(coerce(QQ,5))
        <type 'sage.rings.rational.Rational'>
    """
    try:
        return P._coerce_(x)
    except AttributeError:
        return P(x)