naucse.python.cz
naucse.python.cz copied to clipboard
Pyglet: Use decorators maybe?
In https://github.com/pyvec/naucse.python.cz/blob/master/lessons/snake/drawing/index.md we use decorators, but in https://github.com/pyvec/naucse.python.cz/blob/master/lessons/intro/pyglet/index.md we don't. I prefer to use them. What's the benefit of not using them? Also, in Asteroids.
This decorator?
@window.event
def on_draw():
I like it too, but I already see how some students are going to get burn :) The problem is that the window
object must be defined. So it can cause problems when someone has different order of things in source code file.
Is the window object light-weight, so is it ok to create it even if the file is imported just for tests, not for actual game run?
But the non-decorator approach - window.push_handlers(on_text=zpracuj_text, on_draw=vykresli)
was pretty chaotic to manage last time - too many stuff to check, no apparent info why it doesn't work when it doesn't if someone forgot to update push_handlers
.
The push_handlers
way is used because:
- I didn't want to have to explain how exactly decorators work. (Now I know that's unnecessary, it's enough to show how they're used and what they to conceptually.)
- To show that functions can be passed around as values. (That would, perhaps, instead warrant its own lesson on an advanced course. @frenzymadness?)
But you're right; the lesson will be better with decorators instead. They're much more useful than those two concepts – besides pyglet you'll see them in Click, Flask, etc.
I think that is not that hard to explain how decorators work without going too deep - I mean in simple usages like pyglet or flask where they are used mostly for function registration.
I'll prepare an advance lesson about higher level functions, decorators and functools
module.
Ok, now, after advanced python lesson about higher order functions and decorators, I think that push_handlers
is better.
It's simple to explain that function is still just variable with special content and it can be passed as an argument to other functions but decorators are way more powerful than this and it's not that easy to explain how they work and what they are capable to do.
I think that it's better to explain decorators deeply on advanced courses and don't use them on beginners ones.
Any final decision?
I would like to show decorators, but not talk about functions-as-values or higher-order functions – just like when we don't talk about stack frames when we "explain" how to call a function.