Tuesday, July 21, 2015

Simulating an Argument with Threads and Decorators

Today's Python script demonstrates what an argument sounds like where you have two people trying to talk over one another.  Here's the code to that.



So here's what's interesting about this.

Concurrency
Python supports threads via the threading module.  Theads are good when you need concurrency in your application.  Concurrency means you can set up code and make it seem like more than one thing is happening at the same time.

Creating a thread just requires a target function to "threadify" and arguments to be passed in.  Once you create that thread, you can start it whenever you want.  In the case of this program, the threads are created and started in the same line.  Yup, that was lazy of me.

Python Decorators
Decorators allow for all sorts of neat tricks because they can tweak the behavior of functions by wrapping them.  In this case, the function argue gets passed into what's effectively the concurrent function.  When that happens, it returns the wrapper responsible for turning the function calls into running threads.

Summing Up
I'd say go out and experiment with decorators and threads.  If you're new to either, you're better off learning one or the other rather than both.  Decorators are probably the easier and more useful of the two topics touched on here.  Threads are neat too and can be handy for giving your apps a performance bump in certain situations.  Go ahead and try this out in a Python 3.4 environment, tweak it, and have fun with it.  Cheers.