code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def sources(self) -> SourceManager: # type: ignore[override] """ All the sources in the project. """ return SourceManager( self.path, lambda: self.contracts_folder, exclude_globs=self.exclusions )
All the sources in the project.
sources
python
ApeWorX/ape
src/ape/managers/project.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/project.py
Apache-2.0
def isolate_in_tempdir(self, **config_override) -> Iterator["LocalProject"]: """ Clone this project to a temporary directory and return its project.vers_settings["outputSelection"] """ sources = dict(self.sources.items()) if self.in_tempdir: # Already in a tem...
Clone this project to a temporary directory and return its project.vers_settings["outputSelection"]
isolate_in_tempdir
python
ApeWorX/ape
src/ape/managers/project.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/project.py
Apache-2.0
def load_manifest(self) -> PackageManifest: """ Load a publish-able manifest. Returns: ethpm_types.PackageManifest """ if not self.manifest_path.is_file(): return PackageManifest() try: manifest = _load_manifest(self.manifest_path) ...
Load a publish-able manifest. Returns: ethpm_types.PackageManifest
load_manifest
python
ApeWorX/ape
src/ape/managers/project.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/project.py
Apache-2.0
def extract_manifest(self) -> PackageManifest: """ Get a finalized manifest for publishing. Returns: PackageManifest """ sources = dict(self.sources) contract_types = { n: c.contract_type for n, c in self.load_contracts().items() ...
Get a finalized manifest for publishing. Returns: PackageManifest
extract_manifest
python
ApeWorX/ape
src/ape/managers/project.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/project.py
Apache-2.0
def chdir(self, path: Optional[Path] = None): """ Change the local project to the new path. Args: path (Path): The path of the new project. If not given, defaults to the project's path. """ return ChangeDirectory( self.path, path...
Change the local project to the new path. Args: path (Path): The path of the new project. If not given, defaults to the project's path.
chdir
python
ApeWorX/ape
src/ape/managers/project.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/project.py
Apache-2.0
def reload_config(self): """ Reload the local ape-config.yaml file. This is useful if the file was modified in the active python session. """ self._clear_cached_config() _ = self.config
Reload the local ape-config.yaml file. This is useful if the file was modified in the active python session.
reload_config
python
ApeWorX/ape
src/ape/managers/project.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/project.py
Apache-2.0
def engines(self) -> dict[str, QueryAPI]: """ A dict of all :class:`~ape.api.query.QueryAPI` instances across all installed plugins. Returns: dict[str, :class:`~ape.api.query.QueryAPI`] """ engines: dict[str, QueryAPI] = {"__default__": DefaultQueryProvider(...
A dict of all :class:`~ape.api.query.QueryAPI` instances across all installed plugins. Returns: dict[str, :class:`~ape.api.query.QueryAPI`]
engines
python
ApeWorX/ape
src/ape/managers/query.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/query.py
Apache-2.0
def query( self, query: QueryType, engine_to_use: Optional[str] = None, ) -> Iterator[BaseInterfaceModel]: """ Args: query (``QueryType``): The type of query to execute engine_to_use (Optional[str]): Short-circuit selection logic using a ...
Args: query (``QueryType``): The type of query to execute engine_to_use (Optional[str]): Short-circuit selection logic using a specific engine. Defaults is set by performance-based selection logic. Raises: :class:`~ape.exceptions.QueryEngineError`: Whe...
query
python
ApeWorX/ape
src/ape/managers/query.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/query.py
Apache-2.0
def __setitem__( self, address: AddressType, item: Union[ContractType, ProxyInfoAPI, ContractCreation] ): """ Cache the given contract type. Contracts are cached in memory per session. In live networks, contracts also get cached to disk at ``.ape/{ecosystem_name}/{network_nam...
Cache the given contract type. Contracts are cached in memory per session. In live networks, contracts also get cached to disk at ``.ape/{ecosystem_name}/{network_name}/contract_types/{address}.json`` for faster look-up next time. Args: address (AddressType): The on...
__setitem__
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def cache_contract_type( self, address: AddressType, contract_type: ContractType, ecosystem_key: Optional[str] = None, network_key: Optional[str] = None, ): """ Cache a contract type at the given address for the given network. If not connected, you mus...
Cache a contract type at the given address for the given network. If not connected, you must provider both ``ecosystem_key:`` and ``network_key::``. Args: address (AddressType): The address key. contract_type (ContractType): The contract type to cache. ...
cache_contract_type
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def cache_contract_creation( self, address: AddressType, contract_creation: ContractCreation, ecosystem_key: Optional[str] = None, network_key: Optional[str] = None, ): """ Cache a contract creation object. Args: address (AddressType): The...
Cache a contract creation object. Args: address (AddressType): The address of the contract. contract_creation (ContractCreation): The object to cache. ecosystem_key (str | None): The ecosystem key. Defaults to the connected ecosystem's name. ...
cache_contract_creation
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def __delitem__(self, address: AddressType): """ Delete a cached contract. If using a live network, it will also delete the file-cache for the contract. Args: address (AddressType): The address to remove from the cache. """ del self.contract_types[address] ...
Delete a cached contract. If using a live network, it will also delete the file-cache for the contract. Args: address (AddressType): The address to remove from the cache.
__delitem__
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def use_temporary_caches(self): """ Create temporary context where there are no cached items. Useful for testing. """ caches = self._caches self._caches = {} with self.deployments.use_temporary_cache(): yield self._caches = caches
Create temporary context where there are no cached items. Useful for testing.
use_temporary_caches
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def cache_deployment( self, contract_instance: ContractInstance, proxy_info: Optional[ProxyInfoAPI] = None, detect_proxy: bool = True, ): """ Cache the given contract instance's type and deployment information. Args: contract_instance (:class:`~ap...
Cache the given contract instance's type and deployment information. Args: contract_instance (:class:`~ape.contracts.base.ContractInstance`): The contract to cache. proxy_info (Optional[ProxyInfoAPI]): Pass in the proxy info, if it is known, to avoid...
cache_deployment
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def get_creation_metadata(self, address: AddressType) -> Optional[ContractCreation]: """ Get contract creation metadata containing txn_hash, deployer, factory, block. Args: address (AddressType): The address of the contract. Returns: Optional[:class:`~ape.api.qu...
Get contract creation metadata containing txn_hash, deployer, factory, block. Args: address (AddressType): The address of the contract. Returns: Optional[:class:`~ape.api.query.ContractCreation`]
get_creation_metadata
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def get_multiple( self, addresses: Collection[AddressType], concurrency: Optional[int] = None ) -> dict[AddressType, ContractType]: """ Get contract types for all given addresses. Args: addresses (list[AddressType): A list of addresses to get contract types for. ...
Get contract types for all given addresses. Args: addresses (list[AddressType): A list of addresses to get contract types for. concurrency (Optional[int]): The number of threads to use. Defaults to ``min(4, len(addresses))``. Returns: dict[Add...
get_multiple
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def get( self, address: AddressType, default: Optional[ContractType] = None, fetch_from_explorer: bool = True, proxy_info: Optional[ProxyInfoAPI] = None, detect_proxy: bool = True, ) -> Optional[ContractType]: """ Get a contract type by address. ...
Get a contract type by address. If the contract is cached, it will return the contract from the cache. Otherwise, if on a live network, it fetches it from the :class:`~ape.api.explorers.ExplorerAPI`. Args: address (AddressType): The address of the contract. ...
get
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def _get_proxy_contract_type( self, address: AddressType, proxy_info: ProxyInfoAPI, fetch_from_explorer: bool = True, default: Optional[ContractType] = None, ) -> Optional[ContractType]: """ Combines the discoverable ABIs from the proxy contract and its implem...
Combines the discoverable ABIs from the proxy contract and its implementation.
_get_proxy_contract_type
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def _get_contract_type( self, address: AddressType, fetch_from_explorer: bool = True, default: Optional[ContractType] = None, ) -> Optional[ContractType]: """ Get the _exact_ ContractType for a given address. For proxy contracts, returns the proxy ABIs if ther...
Get the _exact_ ContractType for a given address. For proxy contracts, returns the proxy ABIs if there are any and not the implementation ABIs.
_get_contract_type
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def instance_at( self, address: Union[str, AddressType], contract_type: Optional[ContractType] = None, txn_hash: Optional[Union[str, "HexBytes"]] = None, abi: Optional[Union[list[ABI], dict, str, Path]] = None, fetch_from_explorer: bool = True, proxy_info: Optiona...
Get a contract at the given address. If the contract type of the contract is known, either from a local deploy or a :class:`~ape.api.explorers.ExplorerAPI`, it will use that contract type. You can also provide the contract type from which it will cache and use next time. Raises...
instance_at
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def instance_from_receipt( cls, receipt: "ReceiptAPI", contract_type: ContractType ) -> ContractInstance: """ A convenience method for creating instances from receipts. Args: receipt (:class:`~ape.api.transactions.ReceiptAPI`): The receipt. contract_type (Con...
A convenience method for creating instances from receipts. Args: receipt (:class:`~ape.api.transactions.ReceiptAPI`): The receipt. contract_type (ContractType): The deployed contract type. Returns: :class:`~ape.contracts.base.ContractInstance`
instance_from_receipt
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def get_deployments(self, contract_container: ContractContainer) -> list[ContractInstance]: """ Retrieves previous deployments of a contract container or contract type. Locally deployed contracts are saved for the duration of the script and read from ``_local_deployments_mapping``, while...
Retrieves previous deployments of a contract container or contract type. Locally deployed contracts are saved for the duration of the script and read from ``_local_deployments_mapping``, while those deployed on a live network are written to disk in ``deployments_map.json``. Arg...
get_deployments
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def clear_local_caches(self): """ Reset local caches to a blank state. """ if self.network_manager.connected: for cache in ( self.contract_types, self.proxy_infos, self.contract_creations, self.blueprints, ...
Reset local caches to a blank state.
clear_local_caches
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def get_deployments( self, contract_name: str, ecosystem_key: Optional[str] = None, network_key: Optional[str] = None, ) -> list[Deployment]: """ Get the deployments of the given contract on the currently connected network. Args: contract_name (st...
Get the deployments of the given contract on the currently connected network. Args: contract_name (str): The name of the deployed contract. ecosystem_key (str | None): The ecosystem key. Defaults to the connected ecosystem's name. network_key (str | No...
get_deployments
python
ApeWorX/ape
src/ape/managers/_deploymentscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_deploymentscache.py
Apache-2.0
def cache_deployment( self, address: AddressType, contract_name: str, transaction_hash: Optional[str] = None, ecosystem_key: Optional[str] = None, network_key: Optional[str] = None, ): """ Update the deployments cache with a new contract. Args...
Update the deployments cache with a new contract. Args: address (AddressType): The address of the contract. contract_name (str): The name of the contract type. transaction_hash (Optional[str]): Optionally, the transaction has associated with the deploy...
cache_deployment
python
ApeWorX/ape
src/ape/managers/_deploymentscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_deploymentscache.py
Apache-2.0
def account_types( # type: ignore[empty-body] self, ) -> tuple[type["AccountContainerAPI"], type["AccountAPI"]]: """ A hook for returning a tuple of an account container and an account type. Each account-base plugin defines and returns their own types here. Usage example:: ...
A hook for returning a tuple of an account container and an account type. Each account-base plugin defines and returns their own types here. Usage example:: @plugins.register(plugins.AccountPlugin) def account_types(): return AccountContainer, KeyfileAc...
account_types
python
ApeWorX/ape
src/ape/plugins/account.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/account.py
Apache-2.0
def register_compiler( # type: ignore[empty-body] self, ) -> tuple[tuple[str], type["CompilerAPI"]]: """ A hook for returning the set of file extensions the plugin handles and the compiler class that can be used to compile them. Usage example:: @plugins.registe...
A hook for returning the set of file extensions the plugin handles and the compiler class that can be used to compile them. Usage example:: @plugins.register(plugins.CompilerPlugin) def register_compiler(): return (".json",), InterfaceCompiler ...
register_compiler
python
ApeWorX/ape
src/ape/plugins/compiler.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/compiler.py
Apache-2.0
def config_class(self) -> type["PluginConfig"]: # type: ignore[empty-body] """ A hook that returns a :class:`~ape.api.config.PluginConfig` parser class that can be used to deconstruct the user config options for this plugins. **NOTE**: If none are specified, all injected :class:`ape.ap...
A hook that returns a :class:`~ape.api.config.PluginConfig` parser class that can be used to deconstruct the user config options for this plugins. **NOTE**: If none are specified, all injected :class:`ape.api.config.PluginConfig`'s are empty. Usage example:: @plug...
config_class
python
ApeWorX/ape
src/ape/plugins/config.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/config.py
Apache-2.0
def converters(self) -> Iterator[tuple[str, type["ConverterAPI"]]]: # type: ignore[empty-body] """ A hook that returns an iterator of tuples of a string ABI type and a ``ConverterAPI`` subclass. Usage example:: @plugins.register(plugins.ConversionPlugin) def co...
A hook that returns an iterator of tuples of a string ABI type and a ``ConverterAPI`` subclass. Usage example:: @plugins.register(plugins.ConversionPlugin) def converters(): yield int, MweiConversions Returns: Iterator[tuple[str, ty...
converters
python
ApeWorX/ape
src/ape/plugins/converter.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/converter.py
Apache-2.0
def ecosystems(self) -> Iterator[type["EcosystemAPI"]]: # type: ignore[empty-body] """ A hook that must return an iterator of :class:`ape.api.networks.EcosystemAPI` subclasses. Usage example:: @plugins.register(plugins.EcosystemPlugin) def ecosystems(): ...
A hook that must return an iterator of :class:`ape.api.networks.EcosystemAPI` subclasses. Usage example:: @plugins.register(plugins.EcosystemPlugin) def ecosystems(): yield Ethereum Returns: Iterator[type[:class:`~ape.api.networks.E...
ecosystems
python
ApeWorX/ape
src/ape/plugins/network.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/network.py
Apache-2.0
def networks(self) -> Iterator[tuple[str, str, type["NetworkAPI"]]]: # type: ignore[empty-body] """ A hook that must return an iterator of tuples of: * the target ecosystem plugin's name * the network name * a :class:`ape.api.networks.NetworkAPI` subclass Usage example...
A hook that must return an iterator of tuples of: * the target ecosystem plugin's name * the network name * a :class:`ape.api.networks.NetworkAPI` subclass Usage example:: @plugins.register(plugins.NetworkPlugin) def networks(): yield "...
networks
python
ApeWorX/ape
src/ape/plugins/network.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/network.py
Apache-2.0
def providers( # type: ignore[empty-body] self, ) -> Iterator[tuple[str, str, type["ProviderAPI"]]]: """ A hook that must return an iterator of tuples of: * the target ecosystem plugin's name * the network it works with (which must be valid network in the ecosystem) ...
A hook that must return an iterator of tuples of: * the target ecosystem plugin's name * the network it works with (which must be valid network in the ecosystem) * a :class:`ape.api.providers.ProviderAPI` subclass Usage example:: @plugins.register(plugins.Provider...
providers
python
ApeWorX/ape
src/ape/plugins/network.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/network.py
Apache-2.0
def explorers( # type: ignore[empty-body] self, ) -> Iterator[tuple[str, str, type["ExplorerAPI"]]]: """ A hook that must return an iterator of tuples of: * the target ecosystem plugin's name * the network it works with (which must be valid network in the ecosystem) ...
A hook that must return an iterator of tuples of: * the target ecosystem plugin's name * the network it works with (which must be valid network in the ecosystem) * a :class:`~ape.api.explorers.ExplorerAPI` subclass Usage example:: @plugins.register(plugins.Explore...
explorers
python
ApeWorX/ape
src/ape/plugins/network.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/network.py
Apache-2.0
def projects(self) -> Iterator[type["ProjectAPI"]]: # type: ignore[empty-body] """ A hook that returns a :class:`~ape.api.projects.ProjectAPI` subclass type. Returns: type[:class:`~ape.api.projects.ProjectAPI`] """
A hook that returns a :class:`~ape.api.projects.ProjectAPI` subclass type. Returns: type[:class:`~ape.api.projects.ProjectAPI`]
projects
python
ApeWorX/ape
src/ape/plugins/project.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/project.py
Apache-2.0
def dependencies(self) -> dict[str, type["DependencyAPI"]]: # type: ignore[empty-body] """ A hook that returns a :class:`~ape.api.projects.DependencyAPI` mapped to its ``ape-config.yaml`` file dependencies special key. For example, when configuring GitHub dependencies, you set the ``git...
A hook that returns a :class:`~ape.api.projects.DependencyAPI` mapped to its ``ape-config.yaml`` file dependencies special key. For example, when configuring GitHub dependencies, you set the ``github`` key in the ``dependencies:`` block of your ``ape-config.yaml`` file and it wi...
dependencies
python
ApeWorX/ape
src/ape/plugins/project.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/project.py
Apache-2.0
def query_engines(self) -> Iterator[type["QueryAPI"]]: # type: ignore[empty-body] """ A hook that returns an iterator of types of a ``QueryAPI`` subclasses Usage example:: @plugins.register(plugins.QueryPlugin) def query_engines(): yield PostgresEngine ...
A hook that returns an iterator of types of a ``QueryAPI`` subclasses Usage example:: @plugins.register(plugins.QueryPlugin) def query_engines(): yield PostgresEngine Returns: Iterator[type[:class:`~ape.api.query.QueryAPI`]]
query_engines
python
ApeWorX/ape
src/ape/plugins/query.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/query.py
Apache-2.0
def install_str(self) -> str: """ The strings you pass to ``pip`` to make the install request, such as ``ape-trezor==0.4.0``. """ if self.version and self.version.startswith("git+"): # If the version is a remote, you do `pip install git+http://github...` ...
The strings you pass to ``pip`` to make the install request, such as ``ape-trezor==0.4.0``.
install_str
python
ApeWorX/ape
src/ape/plugins/_utils.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/_utils.py
Apache-2.0
def can_install(self) -> bool: """ ``True`` if the plugin is available and the requested version differs from the installed one. **NOTE**: Is always ``True`` when the plugin is not installed. """ requesting_different_version = ( self.version is not None and ...
``True`` if the plugin is available and the requested version differs from the installed one. **NOTE**: Is always ``True`` when the plugin is not installed.
can_install
python
ApeWorX/ape
src/ape/plugins/_utils.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/_utils.py
Apache-2.0
def prepare_package_manager_args( self, verb: str, python_location: Optional[str] = None, extra_args: Optional[Iterable[str]] = None, ) -> list[str]: """ Build command arguments for pip or uv package managers. Usage: args = prepare_package_manager...
Build command arguments for pip or uv package managers. Usage: args = prepare_package_manager_args("install", "/path/to/python", ["--user"])
prepare_package_manager_args
python
ApeWorX/ape
src/ape/plugins/_utils.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/_utils.py
Apache-2.0
def register(plugin_type: type[PluginType], **hookimpl_kwargs) -> Callable: """ Register your plugin to ape. You must call this decorator to get your plugins included in ape's plugin ecosystem. Usage example:: @plugins.register(plugins.AccountPlugin) # 'register()' example def account...
Register your plugin to ape. You must call this decorator to get your plugins included in ape's plugin ecosystem. Usage example:: @plugins.register(plugins.AccountPlugin) # 'register()' example def account_types(): return AccountContainer, KeyfileAccount Args: pl...
register
python
ApeWorX/ape
src/ape/plugins/__init__.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/__init__.py
Apache-2.0
def gas_exclusions(self) -> list["ContractFunctionPath"]: """ The combination of both CLI values and config values. """ from ape.types.trace import ContractFunctionPath cli_value = self.pytest_config.getoption("--gas-exclude") exclusions = ( [ContractFunction...
The combination of both CLI values and config values.
gas_exclusions
python
ApeWorX/ape
src/ape/pytest/config.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/config.py
Apache-2.0
def _check_dev_message(self, exception: ContractLogicError): """ Attempts to extract a dev-message from the contract source code by inspecting what instruction(s) led to a transaction revert. Raises: AssertionError: When the trace or source can not be retrieved, the dev mess...
Attempts to extract a dev-message from the contract source code by inspecting what instruction(s) led to a transaction revert. Raises: AssertionError: When the trace or source can not be retrieved, the dev message cannot be found, or the found dev message does not match...
_check_dev_message
python
ApeWorX/ape
src/ape/pytest/contextmanagers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/contextmanagers.py
Apache-2.0
def _check_expected_message(self, exception: ContractLogicError): """ Compares the revert message given by the exception to the expected message. Raises: AssertionError: When the exception message is ``None`` or if the message does not match the expected message. ...
Compares the revert message given by the exception to the expected message. Raises: AssertionError: When the exception message is ``None`` or if the message does not match the expected message.
_check_expected_message
python
ApeWorX/ape
src/ape/pytest/contextmanagers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/contextmanagers.py
Apache-2.0
def cover( self, traceback: "SourceTraceback", contract: Optional[str] = None, function: Optional[str] = None, ): """ Track the coverage from the given source traceback. Args: traceback (:class:`~ape.types.trace.SourceTraceback`): Th...
Track the coverage from the given source traceback. Args: traceback (:class:`~ape.types.trace.SourceTraceback`): The class instance containing all the information regarding sources covered for a particular transaction. contract (Optional[str]): Optio...
cover
python
ApeWorX/ape
src/ape/pytest/coverage.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/coverage.py
Apache-2.0
def hit_function(self, contract_source: "ContractSource", method: "MethodABI"): """ Another way to increment a function's hit count. Providers may not offer a way to trace calls but this method is available to still increment function hit counts. Args: contract_sourc...
Another way to increment a function's hit count. Providers may not offer a way to trace calls but this method is available to still increment function hit counts. Args: contract_source (``ContractSource``): A contract with a known source file. method (``MethodAB...
hit_function
python
ApeWorX/ape
src/ape/pytest/coverage.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/coverage.py
Apache-2.0
def names(self) -> list[str]: """ Outputs in correct order for item.fixturenames. Also, injects isolation fixtures if needed. """ result = [] for scope, ls in self.items(): # NOTE: For function scoped, we always add the isolation fixture. if not ls...
Outputs in correct order for item.fixturenames. Also, injects isolation fixtures if needed.
names
python
ApeWorX/ape
src/ape/pytest/fixtures.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/fixtures.py
Apache-2.0
def get_info(self, name: str) -> list: """ Get fixture info. Args: name (str): Returns: list of info """ if name not in self._arg2fixturedefs: return [] return self._arg2fixturedefs[name]
Get fixture info. Args: name (str): Returns: list of info
get_info
python
ApeWorX/ape
src/ape/pytest/fixtures.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/fixtures.py
Apache-2.0
def is_iterating(self, name: str) -> bool: """ True when is a non-function scoped parametrized fixture that hasn't fully iterated. """ if name not in self.parametrized: return False elif not (info_ls := self.get_info(name)): return False ...
True when is a non-function scoped parametrized fixture that hasn't fully iterated.
is_iterating
python
ApeWorX/ape
src/ape/pytest/fixtures.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/fixtures.py
Apache-2.0
def isolation(self, scope: Scope) -> Iterator[None]: """ Isolation logic used to implement isolation fixtures for each pytest scope. When tracing support is available, will also assist in capturing receipts. """ self.set_snapshot(scope) if self._track_transactions: ...
Isolation logic used to implement isolation fixtures for each pytest scope. When tracing support is available, will also assist in capturing receipts.
isolation
python
ApeWorX/ape
src/ape/pytest/fixtures.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/fixtures.py
Apache-2.0
def _exclude_from_gas_report( self, contract_name: str, method_name: Optional[str] = None ) -> bool: """ Helper method to determine if a certain contract / method combination should be excluded from the gas report. """ for exclusion in self.config_wrapper.gas_exclusio...
Helper method to determine if a certain contract / method combination should be excluded from the gas report.
_exclude_from_gas_report
python
ApeWorX/ape
src/ape/pytest/fixtures.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/fixtures.py
Apache-2.0
def fixture(chain_isolation: Optional[bool], **kwargs): """ A thin-wrapper around ``@pytest.fixture`` with extra capabilities. Set ``chain_isolation`` to ``False`` to signal to Ape that this fixture's cached result is the same regardless of block number and it does not need to be invalidated during ...
A thin-wrapper around ``@pytest.fixture`` with extra capabilities. Set ``chain_isolation`` to ``False`` to signal to Ape that this fixture's cached result is the same regardless of block number and it does not need to be invalidated during times or pytest-scoped based chain rebasing. Usage example...
fixture
python
ApeWorX/ape
src/ape/pytest/fixtures.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/fixtures.py
Apache-2.0
def pytest_exception_interact(self, report, call): """ A ``-I`` option triggers when an exception is raised which can be interactively handled. Outputs the full ``repr`` of the failed test and opens an interactive shell using the same console as the ``ape console`` command. """ ...
A ``-I`` option triggers when an exception is raised which can be interactively handled. Outputs the full ``repr`` of the failed test and opens an interactive shell using the same console as the ``ape console`` command.
pytest_exception_interact
python
ApeWorX/ape
src/ape/pytest/runners.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/runners.py
Apache-2.0
def pytest_runtest_setup(self, item): """ By default insert isolation fixtures into each test cases list of fixtures prior to actually executing the test case. https://docs.pytest.org/en/6.2.x/reference.html#pytest.hookspec.pytest_runtest_setup """ if ( not s...
By default insert isolation fixtures into each test cases list of fixtures prior to actually executing the test case. https://docs.pytest.org/en/6.2.x/reference.html#pytest.hookspec.pytest_runtest_setup
pytest_runtest_setup
python
ApeWorX/ape
src/ape/pytest/runners.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/runners.py
Apache-2.0
def pytest_sessionstart(self): """ Called after the `Session` object has been created and before performing collection and entering the run test loop. Removes `PytestAssertRewriteWarning` warnings from the terminalreporter. This prevents warnings that "the `ape` library was alre...
Called after the `Session` object has been created and before performing collection and entering the run test loop. Removes `PytestAssertRewriteWarning` warnings from the terminalreporter. This prevents warnings that "the `ape` library was already imported and so related assert...
pytest_sessionstart
python
ApeWorX/ape
src/ape/pytest/runners.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/runners.py
Apache-2.0
def pytest_collection_finish(self, session): """ Called after collection has been performed and modified. """ outcome = yield # Only start provider if collected tests. if not outcome.get_result() and session.items: self._connect()
Called after collection has been performed and modified.
pytest_collection_finish
python
ApeWorX/ape
src/ape/pytest/runners.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/runners.py
Apache-2.0
def pytest_terminal_summary(self, terminalreporter): """ Add a section to terminal summary reporting. When ``--gas`` is active, outputs the gas profile report. """ if self.config_wrapper.track_gas: self._show_gas_report(terminalreporter) if self.config_wrapper...
Add a section to terminal summary reporting. When ``--gas`` is active, outputs the gas profile report.
pytest_terminal_summary
python
ApeWorX/ape
src/ape/pytest/runners.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/runners.py
Apache-2.0
def line_rate(self) -> float: """ The number of lines hit divided by number of lines. """ if not self.statements: # If there are no statements, rely on fn hit count only. return 1.0 if self.hit_count > 0 else 0.0 # This function has hittable statements. ...
The number of lines hit divided by number of lines.
line_rate
python
ApeWorX/ape
src/ape/types/coverage.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/coverage.py
Apache-2.0
def profile_statement( self, pc: int, location: Optional[SourceLocation] = None, tag: Optional[str] = None ): """ Initialize a statement in the coverage profile with a hit count starting at zero. This statement is ready to accumulate hits as tests execute. Args: ...
Initialize a statement in the coverage profile with a hit count starting at zero. This statement is ready to accumulate hits as tests execute. Args: pc (int): The program counter of the statement. location (Optional[ethpm_types.source.SourceStatement]): The location of ...
profile_statement
python
ApeWorX/ape
src/ape/types/coverage.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/coverage.py
Apache-2.0
def include(self, contract_name: str) -> ContractCoverage: """ Ensure a contract is included in the report. """ for contract in self.contracts: if contract.name == contract_name: return contract # Include the contract. contract_cov = Contract...
Ensure a contract is included in the report.
include
python
ApeWorX/ape
src/ape/types/coverage.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/coverage.py
Apache-2.0
def get_xml(self) -> str: """ The coverage XML report as a string. The XML coverage data schema is meant to be compatible with codecov.io. Thus, some of coverage is modified slightly, and some of the naming conventions (based on 90s Java) won't be super relevant to smart-contract...
The coverage XML report as a string. The XML coverage data schema is meant to be compatible with codecov.io. Thus, some of coverage is modified slightly, and some of the naming conventions (based on 90s Java) won't be super relevant to smart-contract projects.
get_xml
python
ApeWorX/ape
src/ape/types/coverage.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/coverage.py
Apache-2.0
def get_html(self, verbose: bool = False) -> str: """ The coverage HTML report as a string. """ html = self._get_html(verbose=verbose) html_str = tostring(html, encoding="utf8", method="html").decode() return _HTMLPrettfier().prettify(html_str)
The coverage HTML report as a string.
get_html
python
ApeWorX/ape
src/ape/types/coverage.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/coverage.py
Apache-2.0
def prettify(self, html_str: str) -> str: """ This is a custom method not part of the HTMLParser spec that ingests a coverage HTML str, handles the formatting, returns it, and resets this formatter's instance, so that the operation is more functional. """ self.fee...
This is a custom method not part of the HTMLParser spec that ingests a coverage HTML str, handles the formatting, returns it, and resets this formatter's instance, so that the operation is more functional.
prettify
python
ApeWorX/ape
src/ape/types/coverage.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/coverage.py
Apache-2.0
def from_event( cls, event: Union[EventABI, "ContractEvent"], search_topics: Optional[dict[str, Any]] = None, addresses: Optional[list[AddressType]] = None, start_block=None, stop_block=None, ): """ Construct a log filter from an event topic query. ...
Construct a log filter from an event topic query.
from_event
python
ApeWorX/ape
src/ape/types/events.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/events.py
Apache-2.0
def __eq__(self, other: Any) -> bool: """ Check for equality between this instance and another ContractLog instance. If the other object is not an instance of ContractLog, this method returns NotImplemented. This triggers the Python interpreter to call the __eq__ method on the o...
Check for equality between this instance and another ContractLog instance. If the other object is not an instance of ContractLog, this method returns NotImplemented. This triggers the Python interpreter to call the __eq__ method on the other object (i.e., y.__eq__(x)) if it is defined,...
__eq__
python
ApeWorX/ape
src/ape/types/events.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/events.py
Apache-2.0
def begin_lineno(self) -> Optional[int]: """ The first line number in the sequence. """ stmts = self.source_statements return stmts[0].begin_lineno if stmts else None
The first line number in the sequence.
begin_lineno
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def ws_begin_lineno(self) -> Optional[int]: """ The first line number in the sequence, including whitespace. """ stmts = self.source_statements return stmts[0].ws_begin_lineno if stmts else None
The first line number in the sequence, including whitespace.
ws_begin_lineno
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def line_numbers(self) -> list[int]: """ The list of all line numbers as part of this node. """ if self.begin_lineno is None: return [] elif self.end_lineno is None: return [self.begin_lineno] return list(range(self.begin_lineno, self.end_lineno...
The list of all line numbers as part of this node.
line_numbers
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def extend( self, location: "SourceLocation", pcs: Optional[set[int]] = None, ws_start: Optional[int] = None, ): """ Extend this node's content with other content that follows it directly. Raises: ValueError: When there is a gap in content. ...
Extend this node's content with other content that follows it directly. Raises: ValueError: When there is a gap in content. Args: location (SourceLocation): The location of the content, in the form (lineno, col_offset, end_lineno, end_coloffset). ...
extend
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def format(self, use_arrow: bool = True) -> str: """ Format this trace node into a string presentable to the user. """ # NOTE: Only show last 2 statements. relevant_stmts = self.statements[-2:] content = "" end_lineno = self.content.end_lineno for stmt i...
Format this trace node into a string presentable to the user.
format
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def next_statement(self) -> Optional[SourceStatement]: """ Returns the next statement that _would_ execute if the program were to progress to the next line. """ # Check for more statements that _could_ execute. if not self.source_statements: return None ...
Returns the next statement that _would_ execute if the program were to progress to the next line.
next_statement
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def extend(self, __iterable) -> None: """ Append all the control flows from the given traceback to this one. """ if not isinstance(__iterable, SourceTraceback): raise TypeError("Can only extend another traceback object.") self.root.extend(__iterable.root)
Append all the control flows from the given traceback to this one.
extend
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def format(self) -> str: """ Get a formatted traceback string for displaying to users. """ if not len(self.root): # No calls. return "" header = "Traceback (most recent call last)" indent = " " last_depth = None segments: list[str...
Get a formatted traceback string for displaying to users.
format
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def add_jump( self, location: "SourceLocation", function: Function, depth: int, pcs: Optional[set[int]] = None, source_path: Optional[Path] = None, ): """ Add an execution sequence from a jump. Args: location (``SourceLocation``): ...
Add an execution sequence from a jump. Args: location (``SourceLocation``): The location to add. function (``Function``): The function executing. source_path (Optional[``Path``]): The path of the source file. depth (int): The depth of the function call i...
add_jump
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def extend_last(self, location: "SourceLocation", pcs: Optional[set[int]] = None): """ Extend the last node with more content. Args: location (``SourceLocation``): The location of the new content. pcs (Optional[set[int]]): The PC values to add on. """ if...
Extend the last node with more content. Args: location (``SourceLocation``): The location of the new content. pcs (Optional[set[int]]): The PC values to add on.
extend_last
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def add_builtin_jump( self, name: str, _type: str, full_name: Optional[str] = None, source_path: Optional[Path] = None, pcs: Optional[set[int]] = None, ): """ A convenience method for appending a control flow that happened from an internal comp...
A convenience method for appending a control flow that happened from an internal compiler built-in code. See the ape-vyper plugin for a usage example. Args: name (str): The name of the compiler built-in. _type (str): A str describing the type of check. ...
add_builtin_jump
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def read_data_from_stream(self, stream): """ Override to pad the value instead of raising an error. """ data_byte_size: int = self.data_byte_size # type: ignore data = stream.read(data_byte_size) if len(data) != data_byte_size: # Pad the value (instead of ra...
Override to pad the value instead of raising an error.
read_data_from_stream
python
ApeWorX/ape
src/ape/utils/abi.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/abi.py
Apache-2.0
def is_struct(outputs: Union[ABIType, Sequence[ABIType]]) -> bool: """ Returns ``True`` if the given output is a struct. """ outputs_seq = outputs if isinstance(outputs, (tuple, list)) else [outputs] return ( len(outputs_seq) == 1 and "[" not in outputs_seq[0].type and outpu...
Returns ``True`` if the given output is a struct.
is_struct
python
ApeWorX/ape
src/ape/utils/abi.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/abi.py
Apache-2.0
def create_struct(name: str, types: Sequence[ABIType], output_values: Sequence) -> Any: """ Create a dataclass representing an ABI struct that can be used as inputs or outputs. The struct properties can be accessed via ``.`` notation, as keys in a dictionary, or numeric tuple access. **NOTE**: This...
Create a dataclass representing an ABI struct that can be used as inputs or outputs. The struct properties can be accessed via ``.`` notation, as keys in a dictionary, or numeric tuple access. **NOTE**: This method assumes you already know the values to give to the struct properties. Args: ...
create_struct
python
ApeWorX/ape
src/ape/utils/abi.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/abi.py
Apache-2.0
def encode_topics(abi: EventABI, topics: Optional[dict[str, Any]] = None) -> list[HexStr]: """ Encode the given topics using the given ABI. Useful for searching logs. Args: abi (EventABI): The event. topics (dict[str, Any] } None): Topic inputs to encode. Returns: list[str]: En...
Encode the given topics using the given ABI. Useful for searching logs. Args: abi (EventABI): The event. topics (dict[str, Any] } None): Topic inputs to encode. Returns: list[str]: Encoded topics.
encode_topics
python
ApeWorX/ape
src/ape/utils/abi.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/abi.py
Apache-2.0
def provider(cls) -> "ProviderAPI": """ The current active provider if connected to one. Raises: :class:`~ape.exceptions.ProviderNotConnectedError`: When there is no active provider at runtime. Returns: :class:`~ape.api.providers.ProviderAPI` ...
The current active provider if connected to one. Raises: :class:`~ape.exceptions.ProviderNotConnectedError`: When there is no active provider at runtime. Returns: :class:`~ape.api.providers.ProviderAPI`
provider
python
ApeWorX/ape
src/ape/utils/basemodel.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/basemodel.py
Apache-2.0
def get(self, name: str) -> Optional[Any]: """ Get an attribute. Args: name (str): The name of the attribute. Returns: Optional[Any]: The attribute if it exists, else ``None``. """ res = self._get(name) if res is not None: re...
Get an attribute. Args: name (str): The name of the attribute. Returns: Optional[Any]: The attribute if it exists, else ``None``.
get
python
ApeWorX/ape
src/ape/utils/basemodel.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/basemodel.py
Apache-2.0
def __getattr__(self, name: str) -> Any: """ An overridden ``__getattr__`` implementation that takes into account :meth:`~ape.utils.basemodel.ExtraAttributesMixin.__ape_extra_attributes__`. """ _assert_not_ipython_check(name) private_attrs = (self.__pydantic_private__ or ...
An overridden ``__getattr__`` implementation that takes into account :meth:`~ape.utils.basemodel.ExtraAttributesMixin.__ape_extra_attributes__`.
__getattr__
python
ApeWorX/ape
src/ape/utils/basemodel.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/basemodel.py
Apache-2.0
def __dir__(self) -> list[str]: """ **NOTE**: Should integrate options in IPython tab-completion. https://ipython.readthedocs.io/en/stable/config/integrating.html """ # Filter out protected/private members return [member for member in super().__dir__() if not member.start...
**NOTE**: Should integrate options in IPython tab-completion. https://ipython.readthedocs.io/en/stable/config/integrating.html
__dir__
python
ApeWorX/ape
src/ape/utils/basemodel.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/basemodel.py
Apache-2.0
def _model_read_file(cls, path: Path) -> dict: """ Get the file's raw data. This is different from ``model_dump()`` because it reads directly from the file without validation. """ if json_str := path.read_text(encoding="utf8") if path.is_file() else "": return json.lo...
Get the file's raw data. This is different from ``model_dump()`` because it reads directly from the file without validation.
_model_read_file
python
ApeWorX/ape
src/ape/utils/basemodel.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/basemodel.py
Apache-2.0
def model_dump_file(self, path: Optional[Path] = None, **kwargs): """ Save this model to disk. Args: path (Optional[Path]): Optionally provide the path now if one wasn't declared at init time. If given a directory, saves the file in that dir with the name...
Save this model to disk. Args: path (Optional[Path]): Optionally provide the path now if one wasn't declared at init time. If given a directory, saves the file in that dir with the name of class with a .json suffix. **kwargs: Extra kwar...
model_dump_file
python
ApeWorX/ape
src/ape/utils/basemodel.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/basemodel.py
Apache-2.0
def model_validate_file(cls, path: Path, **kwargs): """ Validate a file. Args: path (Optional[Path]): Optionally provide the path now if one wasn't declared at init time. **kwargs: Extra kwargs to pass to ``.model_validate_json()``. """ data...
Validate a file. Args: path (Optional[Path]): Optionally provide the path now if one wasn't declared at init time. **kwargs: Extra kwargs to pass to ``.model_validate_json()``.
model_validate_file
python
ApeWorX/ape
src/ape/utils/basemodel.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/basemodel.py
Apache-2.0
def _get_distributions(pkg_name: Optional[str] = None) -> list: """ Get a mapping of top-level packages to their distributions. """ distros = [] all_distros = distributions() for dist in all_distros: package_names = (dist.read_text("top_level.txt") or "").split() for name in pac...
Get a mapping of top-level packages to their distributions.
_get_distributions
python
ApeWorX/ape
src/ape/utils/misc.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py
Apache-2.0
def pragma_str_to_specifier_set(pragma_str: str) -> Optional[SpecifierSet]: """ Convert the given pragma str to a ``packaging.version.SpecifierSet`` if possible. Args: pragma_str (str): The str to convert. Returns: ``Optional[packaging.version.SpecifierSet]`` """ pragma_pa...
Convert the given pragma str to a ``packaging.version.SpecifierSet`` if possible. Args: pragma_str (str): The str to convert. Returns: ``Optional[packaging.version.SpecifierSet]``
pragma_str_to_specifier_set
python
ApeWorX/ape
src/ape/utils/misc.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py
Apache-2.0
def get_package_version(obj: Any) -> str: """ Get the version of a single package. Args: obj: object to search inside for ``__version__``. Returns: str: version string. """ # If value is already cached/static if hasattr(obj, "__version__"): return obj.__version__ ...
Get the version of a single package. Args: obj: object to search inside for ``__version__``. Returns: str: version string.
get_package_version
python
ApeWorX/ape
src/ape/utils/misc.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py
Apache-2.0
def 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``. Args: path (s...
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``. Args: path (str): path to filesystem to find. expand_envars (bool): ``True`` the variab...
load_config
python
ApeWorX/ape
src/ape/utils/misc.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py
Apache-2.0
def 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 :class:`ape.api.providers.ProviderAPI` implementations. Args: tx_error (Exception): The error that occurred when trying to...
Get an error message containing the given error and an explanation of how the gas estimation failed, as in :class:`ape.api.providers.ProviderAPI` implementations. Args: tx_error (Exception): The error that occurred when trying to estimate gas. Returns: str: An error message explaining...
gas_estimation_error_message
python
ApeWorX/ape
src/ape/utils/misc.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py
Apache-2.0
def extract_nested_value(root: Mapping, *args: str) -> Optional[dict]: """ 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") 'VALUE' Args:...
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") 'VALUE' Args: root (dict): Nested keys to form arguments. Returns: dic...
extract_nested_value
python
ApeWorX/ape
src/ape/utils/misc.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py
Apache-2.0
def 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. Args: str_list (list[str]): The list of strings that need padding. ...
Append spacing to each string in a list of strings such that they all have the same length. Args: 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 ...
add_padding_to_strings
python
ApeWorX/ape
src/ape/utils/misc.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py
Apache-2.0
def raises_not_implemented(fn): """ Decorator for raising helpful not implemented error. """ def inner(*args, **kwargs): raise _create_raises_not_implemented_error(fn) # This is necessary for doc strings to show up with sphinx inner.__doc__ = fn.__doc__ return inner
Decorator for raising helpful not implemented error.
raises_not_implemented
python
ApeWorX/ape
src/ape/utils/misc.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py
Apache-2.0
def to_int(value: Any) -> int: """ Convert the given value, such as hex-strs or hex-bytes, to an integer. """ if isinstance(value, int): return value elif isinstance(value, str): return int(value, 16) if is_0x_prefixed(value) else int(value) elif isinstance(value, bytes): ...
Convert the given value, such as hex-strs or hex-bytes, to an integer.
to_int
python
ApeWorX/ape
src/ape/utils/misc.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py
Apache-2.0
def run_until_complete(*item: Any) -> Any: """ Completes the given coroutine and returns its value. Args: *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. ...
Completes the given coroutine and returns its value. Args: *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. Returns: (Any): The value that results ...
run_until_complete
python
ApeWorX/ape
src/ape/utils/misc.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py
Apache-2.0
def is_evm_precompile(address: str) -> bool: """ Returns ``True`` if the given address string is a known Ethereum pre-compile address. Args: address (str): Returns: bool """ try: address = address.replace("0x", "") return 0 < sum(int(x) for x in address) < 1...
Returns ``True`` if the given address string is a known Ethereum pre-compile address. Args: address (str): Returns: bool
is_evm_precompile
python
ApeWorX/ape
src/ape/utils/misc.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py
Apache-2.0
def is_zero_hex(address: str) -> bool: """ Returns ``True`` if the hex str is only zero. **NOTE**: Empty hexes like ``"0x"`` are considered zero. Args: address (str): The address to check. Returns: bool """ try: if addr := address.replace("0x", ""): ret...
Returns ``True`` if the hex str is only zero. **NOTE**: Empty hexes like ``"0x"`` are considered zero. Args: address (str): The address to check. Returns: bool
is_zero_hex
python
ApeWorX/ape
src/ape/utils/misc.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py
Apache-2.0
def _dict_overlay(mapping: dict[str, Any], overlay: dict[str, Any], depth: int = 0): """Overlay given overlay structure on a dict""" for key, value in overlay.items(): if isinstance(value, dict): if key not in mapping: mapping[key] = dict() _dict_overlay(mapping[k...
Overlay given overlay structure on a dict
_dict_overlay
python
ApeWorX/ape
src/ape/utils/misc.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py
Apache-2.0
def log_instead_of_fail(default: Optional[Any] = None): """ A decorator for logging errors instead of raising. This is useful for methods like __repr__ which shouldn't fail. """ def wrapper(fn): @functools.wraps(fn) def wrapped(*args, **kwargs): try: if a...
A decorator for logging errors instead of raising. This is useful for methods like __repr__ which shouldn't fail.
log_instead_of_fail
python
ApeWorX/ape
src/ape/utils/misc.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py
Apache-2.0