Best practice: Sharing object between different objects

Michael Torrie torriem at gmail.com
Mon Feb 23 16:10:07 EST 2015


On 02/23/2015 01:02 PM, sohcahtoa82 at gmail.com wrote:
> That behavior always trips me up.  My intuition tells me that every
> time you import a module, it re-runs the code in the module.  So if I
> had a simple module named myModule.py that had a single line with
> `myInt = 1`, then I would *EXPECT* this behavior:

Basically your intuition is wrong, but I'm not really sure why you think
this in the first place, especially if you're familiar with design
patterns.  A module is a singleton.  Plain and simple.  If you expect a
module to reinstantiate something every time you import it, then what
you want is a class, not a module.

Even if you think of modules like C header files, as far as use goes,
you wouldn't be too far wrong.  Generally speaking header files are
processed only once no matter how many times they are included (at least
the common ones with #ifdef fences in them).

I can see how coming from PHP would trip you up, though.  Of course I
never got the hang of include vs include_once vs require vs require_once.



More information about the Python-list mailing list