Variable Python Decorators
Python decorators and variables
To implement an exponential backoff feature in the mnubo’s python SDK, I used a module called tenacity.
Coming from Java land, decorators are a little bit like annotation. To use an annotation, you slap @something
onto a method/class/variable and you can do a bunch of things with them:
- generate documentation
- describe behaviour
- etc.
To learn more go here.
One limitation of the Java annotation is that you can’t pass runtime variables to them. You can’t do something like that:
public class MyAnnotation {
private int number;
public MyAnnotation(int number) {
this.number = number;
}
@Annotation(defaultNumber = number) // fails with: Attribute value must be a constant
public void doSomething() { }
}
@interface Annotation {
int defaultNumber() default 1;
}
Fortunately, most of the time (except with frameworks like Spring), an annotation is quite easily inspected and the same result can be obtained rather easily without the use of the annotation.
So when I stumbled onto decorators in Python, I wondered if the usage of decorators were limited like Java’s annotation.
It’s not. Since functions in Python are first class objects, a decorator is only a wrapper on a function. To use retry
from tenacity
and alter its behaviour with runtime variables, I created my own decorator on top of it.
You can find an example here: https://gist.github.com/daddykotex/ce00b02917fc8f21240395619424abee.