best way to share an instance of a class among modules?

Rick Johnson rantingrickjohnson at gmail.com
Thu Feb 7 21:14:09 EST 2013


On Wednesday, February 6, 2013 7:36:28 PM UTC-6, Ethan Furman wrote:
> As Michael Torrie pointed out, the 'global' keyword is needed:

Wrong. The global keyword is in fact NOT needed and something i consider to be another wart of the language (PyWart on this subject coming soon!). 

Now, whilst Micheal's advice is valid python code, i would strongly suggest against encouraging people to use the global keyword when they could simply declare the variable beforehand. I know what you are thinking:

""" But python does not /require/ us to declare global variables if we use the global keyword"""

Yes, i know. But i just hate to have variables created "magically" in the middle of execution! ESPECIALLY if these variables are going to be accessed from another module(s). *sniff-sniff* does anyone smell what i smell?

Listen. I want to know every variable and every CONSTANT that will exist in the module namespace, and i want to know these facts BEFORE i read anything else. So please declare them at the top of each module. 


Hierarchy of module code structure:

 0. shebang lines
 1. stdlib import statements
 2. 3rd party and dependency import statements
 3. CONSTANTS
 4. $globalVariables
 5. module functions
 6. module classes (bka: Object Definitions)
 7. Testing Area
 
So if you want to use "global variables" , (bka: Module level variables), then simply declare them with a None value like this:

globalVariable = None

But don't pat yourself on the back just yet! Place a little comment so the reader will understand that this variable is accessed from ANOTHER namespace.

sharedCursor = None # Set by "Class.blah"; Whored out to X,Y and Z!

In this manner i will not be blindsided by proper use of poor language features.



More information about the Python-list mailing list