Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Easier way to check if a piece of middleware is already added #3089

Closed
antazoey opened this issue Aug 30, 2023 · 2 comments
Closed

Easier way to check if a piece of middleware is already added #3089

antazoey opened this issue Aug 30, 2023 · 2 comments

Comments

@antazoey
Copy link
Contributor

antazoey commented Aug 30, 2023

  • Version: 6.8.0
  • Python: 3.10
  • OS: macos
  • pip freeze output
not super relevant and really big and full of the weirdest stuff, please dont make me

What was wrong?

OK, right now if you try to add middleware that already exists, youll hit this line: https://github.com/ethereum/web3.py/blob/main/web3/datastructures.py#L174

            if name is element:
                raise ValueError("You can't add the same un-named instance twice")

and one way to handle this downstream is like this:

            try:
                self.web3.middleware_onion.inject(geth_poa_middleware, layer=0)
            except ValueError as err:
                if "You can't add the same un-named instance twice" in str(err):
                    # Already added
                    pass
                else:
                    raise  # Original error

but it doesn't seem very reliable and try/except is always a last-resort.

How can it be fixed?

Add a method, perhaps __contains__, that allows me to only add middleware if it is not already added.
I'd like to write it like this:

if geth_poa_middleware not in self.web3.middleware_onion:
    self.web3.middleware_onion.inject(geth_poa_middleware, layer=0)

Alternatively, a custom error would work:

try:
    self.web3.middleware_onion.inject(geth_poa_middleware, layer=0)
except MiddlewareAlreadyAddedError:
    pass  # Is ok

Note: We prefer to use issues to track our work. If you think you've encountered a bug in web3py or
have a feature request, you're in the right place. If you have implementation or usage questions,
please refer to our documentation and/or join the conversation
on discord.

@antazoey
Copy link
Contributor Author

dang, it is there! oops not sure what i was doing wrong

@fselmo
Copy link
Collaborator

fselmo commented Aug 30, 2023

@antazoey no worries. Glad you got it working 👍🏼

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants