Back to glossary

Modules (Vyper Code Example)

Reuse code with modules.

Importing modules

math.vy

# pragma version ^0.4.0

# Pure function can easily be reused in importing module
@pure
def mul(x: uint256, y: uint256) -> uint256:
    return x * y

# Not included in final code if not used by importing module
@pure
def div(x: uint256, y: uint256) -> uint256:
    return x // y

auth.vy

# pragma version ^0.4.0

# Not export to importing module?
owner: public(address)

@deploy
def __init__():
    self.owner = msg.sender

@internal
@view
def _check_owner():
    assert self.owner == msg.sender

# Must be exported by importing module
@external
def set_owner(owner: address):
    self._check_owner()
    self.owner = owner

example_1.vy

# pragma version ^0.4.0

import auth
import math

# Need to call auth.__init__()
initializes: auth
# Exports auth.set_owner and auth.owner
exports: (auth.set_owner, auth.owner)

my_num: public(uint256)

@deploy
def __init__():
    auth.__init__()

# Example of calling auth._check_owner
@external
def set_my_num(x: uint256):
    auth._check_owner()
    self.my_num = x

# Example of reading auth.owner
@external
@view
def get_owner() -> address:
    return auth.owner

# Example of importing and using a pure function
@external
@pure
def my_func(x: uint256, y: uint256) -> uint256:
    return math.mul(x, y)

The use statement

auth_2_step.vy

# pragma version ^0.4.0
import auth

# This contract is not a valid contract. auth.__init__() must be called
# by a contract that imports and uses this contract

uses: auth

pending_owner: address

@deploy
def __init__():
    pass

@external
def begin_transfer(new_owner: address):
    auth._check_owner()
    self.pending_owner = new_owner

@external
def accept_transfer():
    assert msg.sender == self.pending_owner
    auth.owner = msg.sender
    self.pending_owner = empty(address)

example_2.vy

# pragma version ^0.4.0

import auth
import auth_2_step

initializes: auth
# auth is dependency of auth_2_step
initializes: auth_2_step[auth := auth]

# export all external functions
exports: auth_2_step.__interface__

@deploy
def __init__():
    auth.__init__()
    auth_2_step.__init__()

Related Terms

No items found.