Vyper theorytheory 0/50 · 0%
Types · medium

26. Type conversions with convert()

Explicit, checked conversions between types.

Vyper never converts types implicitly. `convert(value, TargetType)` performs a checked conversion, reverting if the value can't be represented in the target type (e.g. converting a negative `int256` to `uint256`).

@external
@pure
def to_uint(x: int128) -> uint256:
    assert x >= 0, "negative value"
    return convert(x, uint256)

@external
@pure
def to_bytes(x: uint256) -> bytes32:
    return convert(x, bytes32)

Because conversions are checked, they double as a lightweight assertion — a failed `convert()` is a clear signal something upstream produced an unexpected value.

Check your understanding

  1. 1. How do you convert between types in Vyper?

  2. 2. What happens converting a negative int128 to uint256 without checks?

  3. 3. Why is a failed convert() actually useful?