Skip to content

Commit d594b52

Browse files
committed
Classes inheriting from Web3 did not attach modules appropriately
* Bug fix: On the first run of ``attach_modules()``, ``w3`` should be ``None`` and the ``parent_module`` is the ``Web3`` class. We should look for this condition and set ``w3 = parent_module``. We couldn't use a simple ``isinstance()`` due to a circular import, but we can import it locally if ``w3`` is ``None``. This allows classes to inherit from ``Web3`` without needing to validate that the class name is ``Web3``. This also allows modules to not need to set a ``w3`` if they don't need one, as the older code was intended to do.
1 parent c48c8cb commit d594b52

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

newsfragments/2592.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Allow classes to inherit from the ``Web3`` class by attaching modules appropriately.
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from web3 import (
2+
EthereumTesterProvider,
3+
Web3,
4+
)
5+
6+
7+
def test_classes_may_inherit_from_web3():
8+
class InheritsFromWeb3(Web3):
9+
pass
10+
11+
inherited_w3 = InheritsFromWeb3(EthereumTesterProvider())
12+
assert inherited_w3.eth.chain_id == 131277322940537

web3/_utils/module.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,14 @@ def attach_modules(
5555
" The web3 object already has an attribute with that name"
5656
)
5757

58-
# The parent module is the ``Web3`` instance on first run of the loop
59-
if type(parent_module).__name__ == "Web3":
60-
w3 = parent_module
58+
# The parent module is the ``Web3`` instance on first run of the loop and w3 is
59+
# None. Thus, set w3 to the parent_module. The import needs to happen locally
60+
# due to circular import issues.
61+
if w3 is None:
62+
from web3 import Web3
63+
64+
if isinstance(parent_module, Web3):
65+
w3 = parent_module
6166

6267
module_init_params = _validate_init_params_and_return_if_found(module_class)
6368
if len(module_init_params) == 1:

0 commit comments

Comments
 (0)