Skip to content
Advertisement

Python try_decorator to retry i2c connections

I am communicating with some hardware over an I2C bus.

Every so often, there is an exception as the bus is busy so I am currently handling this with a loop that retries, but there’s a lot of code repetition, I want to tidy it up.

So, I tried to write a decorator function to pass various functions to

As an example, this command initialises the bus: i2c = busio.I2C(board.SCL, board.SDA)

This is the decorator I have written:

JavaScript

And then I try to pass it the line mentioned above as a partial: i2c = try_decorator(partial(busio.I2C, board.SCL, board.SDA), 'i2c init') but I get an exception when I then try and pass the i2c to the next function: 'NoneType' object has no attribute 'try_lock' which I think means the partial isn’t actually initialising the bus properly. I also tried as a lambda and as a function but get similar results.

What can I do to fix this and keep my code as straightforward as possible?

Also, instead of passing a string as name as an arg (to track exceptions), I tried using func.name in the decorator when I tried as a function instead of a partial but it gives an error that seems as if it is trying to get the name of the I2C object.

Edit: I have updated my code as per BigBro’s answer to below but I still get an error when passing the i2c object to my next function (I don’t get this error if I run without the decorator).

JavaScript

'function' object has no attribute 'try_lock'

Advertisement

Answer

The simple answer is that you forgot to return the result of the function in try_decorator (and therefore return None). Replace func() with res = func() and then return res at the end.

However your function is not really a decorator, as it doesn’t actually return a function, and can’t be used as @try_decorator.

I would suggest something like:

JavaScript

output

JavaScript

One last thing, I suggest being more specific in what exception you catch otherwise things might become hard to debug ;)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement