packages, globals, and __builtin__

Laura Creighton lac at cd.chalmers.se
Fri May 11 16:09:00 CEST 2001


Okay, consensus is that I should use a module name inside the package.
Confession time.  I am already doing this.  I've already GOT one, you see.

	<whisper whisper ... CUT TO BATTLEMENTS. THE TAUNTER turns to some 
	others. TAUNTER: `I told 'em  we already got one.' They all giggle.>

I just  as clearly am doing it wrong.  I tried and when it failed, I
concluded that python just absolutely refused to let me have the namespace
I wanted, and cursing I got out the axe of __builtin__ and _really_
forced the issue.  So it's really like this:

My client -- not part of the package:

	import Tkinter
	import Caps.Widgets		

	[... about 10 lines of not related stuff here ...]
	root = Tkinter.Tk()
	userPrefs = Caps.Widgets.UserPreferences()

	import __builtin__
	__builtin__.up = Caps.Widgets.UserPreferences()

	controlMediator = Caps.Widgets.ControlMediator(userPrefs)
	Tkinter.tkinter.createfilehandler(bl, Tkinter.READABLE, bl_handler)
	root.mainloop()

(my main client which doesn't live in the Caps directories)

and then the Caps Widgets.  Currently they all get passed userPrefs
as a parameter, and I really don't want this.

This is (some of) the file Caps/Widgets/UserPreferences.py

class UserPreferences:
    
    def __init__(self):
        # Trust me on this.  You don't want to really see the dictionary
        self.prefs = { # Pretend something reasonable goes here }
        
    def getPreferences(self, key):
        return self.prefs[key]

It's packed with all sorts of goodies such as English and Swedish text
for all the balloons (tool-tips to some of you), the colours you like ...

	(By the way, anybody want to give a shot at translating `Hänvisande'?
	`Referring' will not work, since it is already used to mean
	something quite different.  And `Vaht you _cleecked-on_ t'ge
	dis _Outrageous_ _Message_, you _Silly_ _English_ _ K...kanigget'
	is unlikely to survive code review.  I am using `Forwarding'
	now but I am not entirely happy with it.)

Then I do things now like this:

	a, b, c, d = self.userPrefs.getPreferences(whatever)

which works because I am passing around userPrefs as a parameter.

I don't want to make a new userpref object in the __init__ of every
Widget. I just want one global reference I can get at whenever I like.
And I thought that this was something that python simply refused to
give me.

Is it my __init.py__ file that is no good? This is Caps/Widgets/__init.py__

	import os
	import re

	dir = __path__[0]
	for _file in os.listdir(_dir):
	    if _file != '__init__.py':
	        _m = re.match('(.*)\.py$', _file)
        	if _m != None:
	            exec('from ' + _m.group(1) + ' import *')

Some day I want to make it do lazy loading, but now now.

What have I badly misunderstood?

Thank you for your time and effort.

Laura




More information about the Python-list mailing list