class ape.utils.BaseInterface

Bases: ManagerAccessMixin, ABC

Abstract class that has manager access.

class ape.utils.BaseInterfaceModel

Bases: BaseInterface, BaseModel

An abstract base-class with manager access on a pydantic base model.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_fields: ClassVar[dict[str, FieldInfo]] = {}

Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].

This replaces Model.__fields__ from Pydantic V1.

class ape.utils.ExtraAttributesMixin

Bases: object

A mixin to use on models that provide ExtraModelAttributes. NOTE: Must come _before_ your base-model class in subclass tuple to function.

class ape.utils.ExtraModelAttributes(*, name: str, attributes: Dict[str, Any] | BaseModel | Callable[[], Dict[str, Any] | BaseModel], include_getattr: bool = True, include_getitem: bool = False, additional_error_message: str | None = None)

Bases: BaseModel

A class for defining extra model attributes.

additional_error_message: str | None

An additional error message to include at the end of the normal IndexError message.

attributes: Dict[str, Any] | BaseModel | Callable[[], Dict[str, Any] | BaseModel]

The attributes.

get(name: str) Any | None

Get an attribute.


name (str) – The name of the attribute.


The attribute if it exists, else None.

Return type:


include_getattr: bool

Whether to use these in __getattr__.

include_getitem: bool

Whether to use these in __getitem__.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_fields: ClassVar[dict[str, FieldInfo]] = {'additional_error_message': FieldInfo(annotation=Union[str, NoneType], required=False), 'attributes': FieldInfo(annotation=Union[Dict[str, Any], BaseModel, Callable[list, Union[Dict[str, Any], BaseModel]]], required=True), 'include_getattr': FieldInfo(annotation=bool, required=False, default=True), 'include_getitem': FieldInfo(annotation=bool, required=False, default=False), 'name': FieldInfo(annotation=str, required=True)}

Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].

This replaces Model.__fields__ from Pydantic V1.

name: str

The name of the attributes. This is important in instances such as when an attribute is missing, we can show a more accurate exception message.

class ape.utils.GeneratedDevAccount(address, private_key)

Bases: tuple

An account key-pair generated from the test mnemonic. Set the test mnemonic in your ape-config.yaml file under the test section. Access your test accounts using the test_accounts property.

Config example:

  mnemonic: test test test test test test test test test test test junk
  number_of_accounts: 10

Alias for field number 0


Alias for field number 1

class ape.utils.GithubClient

Bases: object

An HTTP client for the Github API.

property ape_org: Organization



The ApeWorX organization on Github (https

property available_plugins: Set[str]

The available ape plugins, found from looking at the ApeWorX Github organization.


The plugin names as 'ape_plugin_name' (module-like).

Return type:


clone_repo(repo_path: str, target_path: Path, branch: str | None = None, scheme: str = 'http')

Clone a repository from Github.

  • repo_path (str) – The path on Github to the repository, e.g. OpenZeppelin/openzeppelin-contracts.

  • target_path (Path) – The local path to store the repo.

  • branch (Optional[str]) – The branch to clone. Defaults to the default branch.

  • scheme (str) – The git scheme to use when cloning. Defaults to ssh.

download_package(repo_path: str, version: str, target_path: Path)

Download a package from Github. This is useful for managing project dependencies.

  • repo_path (str) – The path on Github to the repository, such as OpenZeppelin/openzeppelin-contracts.

  • version (str) – Number to specify update types to the downloaded package.

  • target_path (path) – A path in your local filesystem to save the downloaded package.

get_release(repo_path: str, version: str) GitRelease

Get a release from Github.

  • repo_path (str) – The path on Github to the repository, e.g. OpenZeppelin/openzeppelin-contracts.

  • version (str) – The version of the release to get. Pass in "latest" to get the latest release.



get_repo(repo_path: str) Repository

Get a repository from GitHub.


repo_path (str) – The path to the repository, such as OpenZeppelin/openzeppelin-contracts.



class ape.utils.JoinableQueue(maxsize=0)

Bases: Queue

A queue that can be joined, useful for multi-processing. Borrowed from the py-geth library.


Blocks until all items in the Queue have been gotten and processed.

The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is complete.

When the count of unfinished tasks drops to zero, join() unblocks.

class ape.utils.Struct

Bases: object

A class for contract return values using the struct data-structure.

items() Dict


class ape.utils.StructParser(method_abi: ConstructorABI | MethodABI | EventABI)

Bases: object

A utility class responsible for parsing structs out of values.

decode_output(values: List | Tuple) Any

Parse a list of output types and values into structs. Values are only altered when they are a struct. This method also handles structs within structs as well as arrays of structs.


values (Union[List, Tuple]) – A list of of output values.


The same input values only decoded into structs when applicable.

Return type:


property default_name: str

The default struct return name for unnamed structs. This value is also used for named tuples where the tuple does not have a name (but each item in the tuple does have a name).

encode_input(values: List | Tuple | Dict) Any

Convert dicts and other objects to struct inputs.


values (Union[List, Tuple]) – A list of of input values.


The same input values only decoded into structs when applicable.

Return type:


class ape.utils.TraceStyles

Bases: object

Colors to use when displaying a call trace. Each item in the class points to the part of the trace it colors.

CONTRACTS = '#ff8c00'

Contract type names.

DELEGATE = '#d75f00'

The part ‘(delegate)’ that appears before delegate calls.

GAS_COST = 'dim'

The gas used of the call.

INPUTS = 'bright_magenta'

Method arguments.

METHODS = 'bright_green'

Method names; not including arguments or return values.

OUTPUTS = 'bright_blue'

Method return values.

VALUE = '#00afd7'

The transaction value, when it’s > 0.

ape.utils.add_padding_to_strings(str_list: List[str], extra_spaces: int = 0, space_character: str = ' ') List[str]

Append spacing to each string in a list of strings such that they all have the same length.

  • str_list (List[str]) – The list of strings that need padding.

  • extra_spaces (int) – Optionally append extra spacing. Defaults to 0.

  • space_character (str) – The character to use in the padding. Defaults to " ".


A list of equal-length strings with padded spaces.

Return type:


ape.utils.allow_disconnected(fn: Callable)

A decorator that instead of raising ProviderNotConnectedError warns and returns None.

Usage example:

from typing import Optional
from ape.types import SnapshotID
from ape.utils import return_none_when_disconnected

def try_snapshot(self) -> Optional[SnapshotID]:
    return self.chain.snapshot()
ape.utils.expand_environment_variables(contents: str) str

Replace substrings of the form $name or ${name} in the given path with the value of environment variable name.


contents (str) – A path-like object representing a file system. A path-like object is either a string or bytes object representing a path.


The given content with all environment variables replaced with their values.

Return type:


ape.utils.extract_nested_value(root: Mapping, *args: str) Dict | None

Dig through a nested dict using the given keys and return the last-found object.

Usage example:

>>> extract_nested_value({"foo": {"bar": {"test": "VALUE"}}}, "foo", "bar", "test")

root (dict) – Nested keys to form arguments.


The final value if it exists else None if the tree ends at any point.

Return type:

dict, optional

ape.utils.gas_estimation_error_message(tx_error: Exception) str

Get an error message containing the given error and an explanation of how the gas estimation failed, as in ape.api.providers.ProviderAPI implementations.


tx_error (Exception) – The error that occurred when trying to estimate gas.


An error message explaining that the gas failed and that the transaction will likely revert.

Return type:


ape.utils.generate_dev_accounts(mnemonic: str = 'test test test test test test test test test test test junk', number_of_accounts: int = 10, hd_path: str = "m/44'/60'/0'/0", start_index: int = 0) List[GeneratedDevAccount]

Create accounts from the given test mnemonic. Use these accounts (or the mnemonic) in chain-genesis for testing providers.

  • mnemonic (str) – mnemonic phrase or seed words.

  • number_of_accounts (int) – Number of accounts. Defaults to 10.

  • hd_path (str) – Hard Wallets/HD Keys derivation path format. Defaults to "m/44'/60'/0'/0".

  • start_index (int) – The index to start from in the path. Defaults to 0.


List of development accounts.

Return type:


ape.utils.get_all_files_in_directory(path: Path, pattern: Pattern | str | None = None) List[Path]

Returns all the files in a directory structure.

For example, given a directory structure like:

dir_a: dir_b, file_a, file_b
dir_b: file_c

and you provide the path to dir_a, it will return a list containing the paths to file_a, file_b and file_c.

  • path (pathlib.Path) – A directory containing files of interest.

  • pattern (Optional[Union[Pattern, str]]) – Optionally provide a regex pattern to match.


A list of files in the given directory.

Return type:


ape.utils.get_current_timestamp_ms() int

Get the current UNIX timestamp in milliseconds.



ape.utils.get_package_version(obj: Any) str

Get the version of a single package.


obj – object to search inside for __version__.


version string.

Return type:


ape.utils.get_relative_path(target: Path, anchor: Path) Path

Compute the relative path of target relative to anchor, which may or may not share a common ancestor.

NOTE: Both paths must be absolute.

  • target (pathlib.Path) – The path we are interested in.

  • anchor (pathlib.Path) – The path we are starting from.


The new path to the target path from the anchor path.

Return type:


class ape.utils.injected_before_use(fget=None, fset=None, fdel=None, doc=None)

Bases: property

Injected properties are injected class variables that must be set before use.

NOTE: do not appear in a Pydantic model’s set of properties.

ape.utils.is_array(abi_type: str | ABIType) bool

Returns True if the given type is a probably an array.


abi_type (Union[str, ABIType]) – The type to check.



ape.utils.is_evm_precompile(address: str) bool

Returns True if the given address string is a known Ethereum pre-compile address.


address (str) –



ape.utils.is_named_tuple(outputs: Sequence[ABIType], output_values: Sequence) bool

Returns True if the given output is a tuple where every item is named.

ape.utils.is_struct(outputs: ABIType | Sequence[ABIType]) bool

Returns True if the given output is a struct.

ape.utils.is_zero_hex(address: str) bool

Returns True if the hex str is only zero. NOTE: Empty hexes like "0x" are considered zero.


address (str) – The address to check.



ape.utils.load_config(path: Path, expand_envars=True, must_exist=False) Dict

Load a configuration file into memory. A file at the given path must exist or else it will throw OSError. The configuration file must be a .json or .yaml or else it will throw TypeError.

  • path (str) – path to filesystem to find.

  • expand_envars (bool) – True the variables in path are able to expand to show full path.

  • must_exist (bool) – True will be set if the configuration file exist and is able to be load.


Configured settings parsed from a config file.

Return type:

Dict (dict)

ape.utils.log_instead_of_fail(default: Any | None = None)

A decorator for logging errors instead of raising. This is useful for methods like __repr__ which shouldn’t fail.

ape.utils.pragma_str_to_specifier_set(pragma_str: str) SpecifierSet | None

Convert the given pragma str to a packaging.version.SpecifierSet if possible.


pragma_str (str) – The str to convert.




Decorator for raising helpful not implemented error.

ape.utils.returns_array(abi: MethodABI) bool

Returns True if the given method ABI likely returns an array.


abi (MethodABI) – An ABI method.



ape.utils.run_until_complete(*item: Any) Any

Completes the given coroutine and returns its value.


*item (Any) – A coroutine or any return value from an async method. If not given a coroutine, returns the given item. Provide multiple coroutines to run tasks in parallel.


The value that results in awaiting the coroutine. Else, item if item is not a coroutine. If given multiple coroutines, returns the result from asyncio.gather.

Return type:


class ape.utils.singledispatchmethod(func)

Bases: object

Single-dispatch generic method descriptor.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

register(cls, func) func

Registers a new implementation for the given cls on a generic_method.

ape.utils.spawn(target, *args, **kwargs)

Spawn a new daemon thread. Borrowed from the py-geth library.

ape.utils.stream_response(download_url: str, progress_bar_description: str = 'Downloading') bytes

Download HTTP content by streaming and returning the bytes. Progress bar will be displayed in the CLI.

  • download_url (str) – String to get files to download.

  • progress_bar_description (str) – Downloading word.


Content in bytes to show the progress.

Return type:


class ape.utils.use_temp_sys_path(path: Path, exclude: List[Path] | None = None)

Bases: object

A context manager to manage injecting and removing paths from a user’s sys paths without permanently modifying it.