2. Properties of functions
1.Functions / Methods are just objects in
python.
All rules of normal objects work exactly - like
assignments etc. [https://gist.github.com/sidchilling/5480003]
Can define one function inside another
function. [https://gist.github.com/sidchilling/5480010]
A function can return another function as well! [
https://gist.github.com/sidchilling/5480019]
3. Properties of functions [contd.]
5. If you can return a function, then you can
pass a function to another function.
[https://gist.github.com/sidchilling/5480024]
4. Decorators, finally!
A decorator is a function which allows you to
execute code before and after a function you
decorate.
What does that mean?
5. What does that mean?
1. A decorator is just a function.
2. Takes the function to decorate as argument.
3. Makes a function inside itself - "the wrapper".
4. The wrapper executes code before and after
calling the function.
5. The decorator just returns the wrapper
function.
[https://gist.github.com/sidchilling/5480027]
6. Properties of decorators
1. Can I make more than one decorator to
decorate a function? Sure, they are just
functions! But order of decorators MATTERS. [
https://gist.github.com/sidchilling/5480034]
2. You can pass arguments to the decorated
function as well. Hint: The wrapper gets the
arguments! [https://gist.github.com/sidchilling/5480041]
3. You can use decorators with methods also -
just take care of self. [https://gist.github.com/sidchilling/5480047]
7. Properties of decorators
4. You can make a generic decorator as well
which will accept any number of arguments -
use of *args and **kwargs come handy in here.
[https://gist.github.com/sidchilling/5480054]
8. Arguments to decorators
Can I pass arguments to decorators itself?
Well... it is a little twisted as the only argument
to a decorator is the decorated function.
But a function can return a function - so a
function can return a decorator as well. This,
we call a "decorator maker" - which returns a
decorator.
[https://gist.github.com/sidchilling/5480066]
9. Arguments to the decorators
It's simple now.
We can obviously pass arguments to the
decorator maker which can then pass
arguments to the decorator and to the wrapper
function as well.
[https://gist.github.com/sidchilling/5480078]
10. Python must be concise!
Basically, all we need is the wrapper function -
the decorator function itself it mostly boiler plate
code.
Can I make it concise?
There are libraries to do so. All you need to
define is the wrapper function.
[https://gist.github.com/sidchilling/5480081]