summaryrefslogtreecommitdiff
path: root/PITCHME.md
blob: 2b902febdcc2de4274c9665d3d33b7c21e60e01f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# The decorator module is alive and kicking

+++

Have you ever heard of the decorator module?

+++

Have you ever heard of IPython?

+++

Every time to fire an IPython instance you are importing
the decorator module :-)

+++

Several frameworks and tools depend on it, so it is one of the most
downloaded packages on PyPI

+++?image=releases.png

+++

**It is joy to maintain**

- next to zero bugs
- few questions
- I usually implement something new only when there is new Python release

+++

For instance

- Python 3.4 generic functions => decorator 4.0
- Python 3.5/3.6 async/await => decorator 4.1
- Python 3.7 dataclasses => decorator 4.2

---

The recommended way to write decorators in Python

```python
from functools import wraps

def trace(f):
    @wraps(f)
    def wrapper(*args, **kwds):
        print('Calling', f.__name__)
        return f(*args, **kwds)
    return wrapper

@trace
def add(x, y):
    """Sum two numbers"""
    return x + y
```
---

```python
>>> inspect.getfullargspec(add)
FullArgSpec(args=[], varargs='args', varkw='kwds', defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={})

>>> add.__code__.co_varnames
('args', 'kwds')
```
---

decorator 0.1, May 2005: *this is a hack, surely they will fix the signature
in the next release of Python*

...

+++

# or maybe no

---

```python
from decorator import decorator

@decorator
def trace(f, *args, **kwds):
    print('Calling', f.__name__)
    return f(*args, **kwds)

@trace
def add(a, b):
    return a + b

>>> add.__code__.co_varnames
('a', 'b')
```

---

```python
@decorator
async def trace(coro, *args, **kwargs):
    print('Calling %s', coro.__name__)
    await coro(*args, **kwargs)

@trace
async def make_task(n):
    for i in range(n):
        await asyncio.sleep(1)

```
---

```python
import warnings
from decorator import decorator

@decorator
def deprecated(func, message='', *args, **kw):
    msg = '%s.%s has been deprecated. %s' % (
        func.__module__, func.__name__, message)
    if not hasattr(func, 'called'):
        warnings.warn(msg, DeprecationWarning, stacklevel=2)
        func.called = 0
    func.called += 1
    return func(*args, **kw)

@deprecated('Use new_function instead')
def old_function():
   'Do something'
```
---
http://decorator.readthedocs.io/en/latest/