예제 #1
0
def test_automatic_promotions():
    class A: pass
    class B(A): pass
    a, b = A(), B()

    assert_allsame(promote(a, b), (a, b))
    assert_allsame(promote(a, a), (a, a))
    assert promote_type(A, B) is A
    assert promote_type(B, A) is A
예제 #2
0
def test_custom_promotions(T1, T2):
    a, b = T1(1), T2(2)

    # Prepare conversions
    set_conversion(T2, T1, lambda x: T1(x.data))
    set_promotion_rule(T1, T2, T1)

    @set_promotion(T1, int, restype=int)
    @set_promotion(T2, int, restype=int)
    def promote_to_int(x, y):
        return convert(x.data, int), y

    # Create examples and test
    assert_allsame(promote(a, b), (a, T1(2)))
    assert_allsame(promote(a, 2), (1, 2))
    assert_allsame(promote(a, b, 3), (1, 2, 3))
    assert_allsame(promote(3, b, a), (3, 2, 1))
예제 #3
0
def test_failed_promotions():
    with pytest.raises(TypeError):
        promote("42", 42)

    with pytest.raises(RuntimeError):
        set_promotion_rule(float, int, int)

    with pytest.raises(RuntimeError):
        set_promotion_rule(int, float, int)

    with pytest.raises(RuntimeError):
        set_promotion(int, float, function=int)

    with pytest.raises(RuntimeError):
        set_promotion(float, int, function=int)

    with pytest.raises(RuntimeError):
        set_promotion_rule(str, str, str)

    with pytest.raises(RuntimeError):
        set_promotion(str, str, function=str)
예제 #4
0
def dtype(values):
    '''Return the dtype for a group of values'''

    if not values:
        raise TypeError('trying to find the type of an empty list')

    values = iter(values)
    value = next(values)
    tt = type(value)

    for v in values:
        if not isinstance(v, tt):
            try:
                value, v = promote(value, v)
                tt = type(value)
            except TypeError:
                tt = commonbase(tt, type(v))
    return tt
예제 #5
0
def test_successfull_promotions_of_base_types():
    assert_allsame(promote(1, 2), (1, 2))
    assert_allsame(promote(1.0, 2.0), (1.0, 2.0))
    assert_allsame(promote(True, 2), (1, 2))
    assert_allsame(promote(2, True), (2, 1))
    assert_allsame(promote(True, 2, 3.0), (1.0, 2.0, 3.0))