[Tutor] Shared State

wolfrage8765 at gmail.com wolfrage8765 at gmail.com
Mon Jul 29 20:30:14 CEST 2013


So this is not specifically Python related as it transcends languages.
 But still I perfer my examples to be in Python since that is the
language I know best.
I want to learn to program in a more functional manor, in fact I am
now reading a book on Erlang, but I still mostly program in Python.  I
want to know how you reduce side-effects in a GUI program, and further
how you handle side effects when you must.  Following is a simple
example for us to work through as it is my current use case.

I have a small program that connects two users together to share
files.  This program is CLI based and thus uses text inputs and
outputs to interact with the user.  It uses threads because I still
find myself needing to share state.  A total of 4 threads: 1 thread
waits on input() (User input), another thread performs background
tasks like checking internet or transfering files, another thread
displays and updates the view or the CLI display, and the final thread
possibly un-needed acts as a Mediator where it notifies listeners of
events or passes messages.

To get to a more functional style program I implemented the mediator
thread, it seems like the best option to reduce side-effects, but the
reason it has not been fully implemented to date is that I felt like I
was violating DRY, as every thread would be storing it's own copy of
the state variables that it cared about.  Is that the best way?  I
have more recently implemented multiprocessing.Manager().NameSpace to
store the shared state across all of the threads.  This is certianly
easier and with less violations of DRY, but is it better, or is it
dangerous (Dead-Lock)?

Back to the program:  It starts up and the worker thread immediately
checks for an internet connection, while the (UI Thread and Input
Thread) UI request that the user tell it if it will host the
connection or be a client to another computer (Refered to as Mode).
Once the Mode is set and a valid internet connection established the
program then obtains the Host IP, either via a site like
whatismyipaddress.com if host, or from user input if client.  Once the
host IP is obtained the program establishes a connection and transfers
the files, during the transfer the UI is updated with the progress.

So what is the best way to organize the program to reduce
side-effects?  Should I use message passing like the Mediator, or
multiprocessing.Manager()?  If you guys really want code I can show
code, but the program is not even Beta quality, and my questions are
more general to implementation.  Plus my code would expand the scope
of the conversation, since it does more than just what was explianed.
Just in case, I am using Python 3.2+ on Linux Mint 64-bit, but my
target market is Windows Users.
Thank you for any and all feedback.


More information about the Tutor mailing list