0

I am working with a beta version of a python library that has renamed a few of the class functions, for instance from "isConnected" to "is_connected". I have different servers with different versions of this library on them and it tends to get annoying to deal with. So far I have till now been dealing with it like:

try:
    from eth_utils.conversions import toHex as to_hex
except ImportError:
    from eth_utils.conversions import to_hex

But this obviously isn't ideal. What I would like to be able to do is something like this:

is_beta = hasattr(eth_utils.conversions, 'to_hex')
if not is_beta:
    setattr(eth_utils.conversions, 'toHex', 'to_hex')

How can this be done? I am guessing that it involves using some metaclass magic?

Edit: The reason why I am looking for a different method here is because I need to initialize web3 like this:

w3 = web3.Web3(web3.HTTPProvider(os.environ.get('ethereum_http_endpoint')))

Then I need to call w3.is_connected:

if w3.is_connected:
    print('Web3 is connected ... now I can do stuff')
else:
    print('Not connected, something wrong, do something else')

So I can't just call is_connected because I specifically need to call the attribute of the object which is created.

Chev_603
  • 313
  • 3
  • 14
  • I'm not sure why you'd prefer the latter over the former, which is fairly clean and readable. But it also seems like you're solving two different problems in the examples. In the former, `to_hex` is something in the global namespace for that module, while in the latter, `to_hex` appears to be some attribute on a class. Just renaming an attribute could break code in the module you're importing, so I would recommend strongly against it. You could do something with inheritance, but tbh I think the original solution might be the preferable one. Unless you have a specific use case where it fails? – Grismar Jan 11 '23 at 00:47
  • I don't know enough about the specific use case, so I don't know if this is better (hence why this is a comment, not an answer), but if you wanted to be explicit about version numbers, [here](https://stackoverflow.com/q/20180543/17769815) might be a good start? – BrokenBenchmark Jan 11 '23 at 00:54
  • No the latter doesn't work, and there is a reason, I will update the question – Chev_603 Jan 11 '23 at 01:05

0 Answers0