Global utility module/package

Christoph Haas email at christoph-haas.de
Mon May 8 18:05:32 EDT 2006


Evening,

I'm currently working on a larger Python project that consists of multiple
programs and packages. As I need a few utility functions time and again I
moved them all into a Utility package and created a class there. Like this:

Util.py:
~~~~~~~~
class Util:
   def __init__(self, debugFlag=False, vibranceLevel='good'):
      self.debugFlag = debugFlag
      self.vibranceLevel = vibranceLevel

   def function1(self):
      do this
      do that

main.py:
~~~~~~~~
import Util
util = Util.Util()
util.function1(whatever)

def some_function():
   global util
   util.function1(dingdong)

However this feels like I'm abusing classes because I don't really need
several instances of an object. I just need one instance. Even worse is
that I'm starting to use "global util" to get access to the "alibi
instance" I created. (I'm not sure whether I could even omit it due to
scoping rules.)

As I know that importing packages from multiple modules always keeps it a
singleton I thought of something like this:

Util.py:
~~~~~~~~
debugFlag = False
vibranceLevel = 'good'

def function1():
   global debugFlag
   print debugFlag

main.py:
~~~~~~~~
import Util
Util.debugFlag = True
Util.function1(whatever)

def doThis():
   Util.function1(42)

Here I don't use classes any longer. Good. But to access the "package
variables" I probably need to use "global" again which just moved the
ugliness to another position.

What would be a good practice here? All I want is a utility package that I
can import from everywhere (as a singleton) and that I can use even in
subroutines (def) without needing to write "global" here. (The "global"
could probably even be omitted because unless I define a variable in a
"def" scope the global variable should be visible.)

Please enlighten me. :)

Kindly
 Christoph

P.S.: Code parts untested. More a schema than something that would actually run.
-- 
Please reply to the list - not to me personally.



More information about the Python-list mailing list