Skip to content

Commit b268803

Browse files
committed
Add details about decorator functions for clarity.
1 parent 7619816 commit b268803

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

sections/software-design-1.qmd

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,12 +39,22 @@ Functions are first-class objects in Python (and many other languages). This has
3939
def double(x):
4040
return 2*x
4141
42+
print(double)
43+
```
44+
45+
```{python}
4246
# also assign the function to the `twotimes` variable
4347
twotimes = double
4448
type(twotimes)
4549
```
4650

47-
Note that when we print it to screen, we see that `prod` is of type `function`, and when we use the two instances, we get identical results:
51+
Note that when we print it to screen, we see that `prod` is of type `function`. We can see from the object address that it is the same object as `double`:
52+
53+
```{python}
54+
print(twotimes)
55+
```
56+
57+
and when we use the two instances, we get identical results:
4858

4959
```{python}
5060
print(double(7))
@@ -81,7 +91,32 @@ Note how we passed the `some_function` as a variable name without the parenthese
8191
::: {.callout-note}
8292

8393
### Decorators
84-
This approach to function composition is exactly what is used by [Python decorator](https://docs.python.org/3/glossary.html#term-decorator) functions.
94+
95+
This approach to function composition is exactly what is used by [Python decorator](https://docs.python.org/3/glossary.html#term-decorator) functions. A `decorator` in python is a function that returns a function, thereby making it easy to wrap the one function inside another. To modify our above exmaple into a decorator, we can simply return the `wrapper` function:
96+
97+
```{python}
98+
def my_decorator(func_to_run):
99+
def wrapper():
100+
print("Ran wrapper")
101+
func_to_run()
102+
print("Finished wrapper")
103+
return wrapper
104+
105+
f = my_decorator(some_function)
106+
107+
f()
108+
```
109+
110+
Finally, once you have a decorator function defined, you can easily apply it to your functions when you define them using some special syntactic sugar, the `@` annotation.
111+
112+
```{python}
113+
@my_decorator
114+
def hello():
115+
print("Hello")
116+
117+
hello()
118+
119+
```
85120

86121
:::
87122

@@ -200,4 +235,6 @@ Deadlocks occur when two concurrent tasks block on the output of the other. Dead
200235

201236
## Further reading
202237

238+
- [Python decorators](https://realpython.com/primer-on-python-decorators/)
239+
- [Python namespaces and scope](https://realpython.com/python-namespaces-scope/)
203240
- [With Statement Context Managers](https://docs.python.org/3/reference/datamodel.html#context-managers)

0 commit comments

Comments
 (0)