On Mon, Dec 15, 2008 at 5:03 PM, Alan Gauld <alan.ga...@btinternet.com> wrote: > > "Marc Tompkins" <marc.tompk...@gmail.com> wrote > >> If you're just starting out in Python, decorators can be hard to get >> your head around... > > I've been using Python for oover 10 years and still find decorators > hard to get my head around! :-) > > I confess I'm not a fan, they go against the Python spirit of > explicit is best in my opinion. If I'm calling a function I like to > know I'm calling a function... I know they make the code look > pretty but IMHO they are a pain to debug and I'm never totally > convinced I've got it exactly right.
I thought this way for a while, but I "get" them now. Mostly I use them as a shortcut to setting some variables on a function, which could later be used for introspection. For instance, a dead simple test framework I wrote uses decorators like this: @test("Just load something",removefiles=["sprite1.txt"],teardown=sprite_cleanup) def load_sprite(): f = open("sprite1.txt","w") f.write("""texture metatex1.png horizontal 2\nvertical 2\nlength 4\nloops 3""") f.close() The decorator signifies to the testing framework that this function should be run, the file sprite1.txt should be removed after running the test, and the function sprite_cleanup should be run as well. This could have been done in other ways, but it is a lot more clear with a decorator. "Hey testing framework, here is how you should run this function" The actual code for the decorator is not complex either: def test(t,removefiles=[],teardown=None): def dec(f): f.a_test = True f.test_desc = t f.removefiles = removefiles f.teardown = teardown return f return dec The function in a function is a bit headache inducing, I'll grant that. But the dec function just sets some variables on the function. This could be done in the old way: def test(f,t,removefiles=[],teardown=None): f.a_test = True f.test_desc = t With the functions decorated like this: def test_sprites: [code] test(test_sprites,"Just load something",removefiles=["sprite1.txt"],teardown=sprite_cleanup) For me though, it is MUCH better to have this information before the function instead of after. Another place I am using them is in an interpreter class. The class has various methods tied to different commands that it understands. I also have a gui where commands can be chosen, according to the category of the command. The decorator is used to add some information that the gui can use about the nature of the command, and which category it falls under. I don't used any advanced features of decorators at all, they just make the code a little bit more clear and allow me to do a bit more introspection of functions for various purposes. I don't use them often, but I do like them. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor