Skip to content

Latest commit

 

History

History
494 lines (335 loc) · 13.4 KB

web3.main.rst

File metadata and controls

494 lines (335 loc) · 13.4 KB

Web3 API

local

Each Web3 instance exposes the following APIs.

Providers

Attributes

Encoding and Decoding Helpers

Currency Conversions

Addresses

Cryptographic Hashing

Check Encodability

RPC API Modules

Each Web3 instance also exposes these namespaced API modules.

These internal modules inherit from the web3.module.Module class which give them some configurations internal to the web3.py library.

Custom Methods

You may add or overwrite methods within any module using the attach_methods function. To create a property instead, set is_property to True.

>>> w3.eth.attach_methods({
...    'example_method': Method(
...      'eth_example',
...       mungers=[...],
...       request_formatters=[...],
...       result_formatters=[...],
...       is_property=False,
...    ),
... })
>>> w3.eth.example_method()

External Modules

External modules can be used to introduce custom or third-party APIs to your Web3 instance. External modules are simply classes whose methods and properties can be made available within the Web3 instance. Optionally, the external module may make use of the parent Web3 instance by accepting it as the first argument within the __init__ function:

>>> class ExampleModule:
...     def __init__(self, w3):
...         self.w3 = w3
...
...     def print_balance_of_shaq(self):
...         print(self.w3.eth.get_balance('shaq.eth'))

Warning

Given the flexibility of external modules, use caution and only import modules from trusted third parties and open source code you've vetted!

Configuring external modules can occur either at instantiation of the Web3 instance or by making use of the attach_modules() method. To instantiate the Web3 instance with external modules use the external_modules keyword argument:

>>> from web3 import Web3, HTTPProvider
>>> from external_module_library import (
...     ModuleClass1,
...     ModuleClass2,
...     ModuleClass3,
...     ModuleClass4,
...     ModuleClass5,
... )
>>> w3 = Web3(
...     HTTPProvider(provider_uri),
...     external_modules={
...         'module1': ModuleClass1,
...         'module2': (ModuleClass2, {
...             'submodule1': ModuleClass3,
...             'submodule2': (ModuleClass4, {
...                 'submodule2a': ModuleClass5,  # submodule children may be nested further if necessary
...             })
...         })
...     }
... )

# `return_zero`, in this case, is an example attribute of the `ModuleClass1` object
>>> w3.module1.return_zero()
0
>>> w3.module2.submodule1.return_one()
1
>>> w3.module2.submodule2.submodule2a.return_two()
2