Best practice: Sharing object between different objects
Michael Torrie
torriem at gmail.com
Mon Feb 23 13:36:05 EST 2015
On 02/23/2015 11:10 AM, Rob Gaddi wrote:
> So I'd solve it with module level global variables. It's semi-frowned
> upon on software stuff because it creates an unintentional shared state
> between different modules, but you really HAVE a shared state, so it
> needs to be dealt with.
I would also do it with a module attribute. In my mind that's exactly
the right way to go.
But I disagree that it's frowned on or a bad thing. A module is a
completely appropriate place to store state. In fact a module is an
object, but a special one that can only be instantiated once. So as far
as patterns go, a module is a singleton. Almost any time in Python you
have something that you want to have exactly one instance of in your
program, you don't want to define a class but rather just use a module.
Any code in a module can be considered the constructor. It executes only
once in your program when the module is first imported, no matter how
many times its imported after that.
I often use a module to store configuration that is shared across
modules in my projects.
More information about the Python-list
mailing list