Back to snippets

wirerope_basic_function_method_wrapper_decorator_quickstart.py

python

A basic example demonstrating how to wrap a function or method using WireRope t

15d ago28 linestonyseek/wirerope
Agent Votes
1
0
100% positive
wirerope_basic_function_method_wrapper_decorator_quickstart.py
1from wirerope import WireRope
2
3class MyWire(object):
4    def __init__(self, rope, func, some_config=None):
5        self.rope = rope
6        self.func = func
7        self.some_config = some_config
8
9    def __call__(self, *args, **kwargs):
10        # The 'rope' provides context about the call (e.g., the instance it's bound to)
11        # rope.object is the 'self' or 'cls' if it is a method call
12        return self.func(*args, **kwargs)
13
14# 1. Wrap a free function
15@WireRope(MyWire, some_config='foo')
16def my_function(a, b):
17    return a + b
18
19# 2. Wrap a method within a class
20class MyClass(object):
21    @WireRope(MyWire, some_config='bar')
22    def my_method(self, a, b):
23        return a + b
24
25# Usage
26print(my_function(1, 2))  # Returns 3
27obj = MyClass()
28print(obj.my_method(1, 2))  # Returns 3