How to use variables across modules

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Nov 3 01:48:46 EDT 2013


On Sat, 02 Nov 2013 14:33:54 -0700, juel4700 wrote:

> Im a newbee at python, and im trying to figure out how to use variables
> and setups across modules.
[...]
> What is best practice for working across modules.

Depends on whether you are working on a framework, a library or an 
application.

Frameworks are monstrously large and complex beasts, not for beginners, 
so I won't discuss them.

Libraries are collections of re-usable code. In general, a library will 
often be in a single module. For example, the math library, which 
contains a collection of re-usable, related functions like sin, cos, tan, 
sqrt, etc.

Some code in an application is re-usable. For instance, if your 
application needs to download data from the Internet, well, lots of apps 
need to download data from the Internet, so it makes sense to pull out 
the download-data-from-the-Internet parts of your application and put 
them into a library module. But the rest of the app is likely to be too 
specific to bother. In that case, it can stay within a single file, at 
least until such point that it grows too large and unwieldy, in which 
case you can start pulling bits out into separate files.

How large is "too large" is a matter of taste, but personally I consider 
the decimal module to be about as large as a single file should get: 
about 6000-7000 lines, including comments and blank lines:

http://hg.python.org/cpython/file/3.3/Lib/decimal.py


Regardless of what you are doing, best practice is that closely related 
code should go together (in the same function, the same class, or the 
same module) and unrelated code should be separate (in a separate 
function, class or module).

Another thing to consider: best practice is to avoid using global 
variables. If you must use them -- and you almost never *need* them -- 
they should be specific to a single module. But better is to not use 
global variables at all. For example, code like this:


value = "something"  # set the global
function()  # call a function
print(result)  # which reads the global "value", and sets global "result"


should be avoided like the plague. Better is to write your functions to 
take input arguments, and return results:

result = function("something")
print(result)


One advantage -- one out of many -- is that if you write your functions 
like this, the question of how to use variables across modules is 
irrelevant. The right answer to the question "What's the best way to 
manage global variables across modules?" is "Don't".



-- 
Steven



More information about the Python-list mailing list