the name of a module in which an instance is created?

Steven Bethard steven.bethard at gmail.com
Mon Nov 21 13:37:37 EST 2005


The setup: I'm working within a framework (designed by someone else) 
that requires a number of module globals to be set.  In most cases, my 
modules look like:
(1) a class definition
(2) the creation of one instance of that class
(3) binding of the instance methods to the appropriate module globals

I'm trying to hide the complexity of step (3) by putting it in a common 
base class.  That way, when I'm writing a new module, I never have to 
see the step (3) code.  Right now, that code is in the __init__ method 
of the common base class and looks something like::

     setattr(mod, 'creole_%s' % name, self._call)
     setattr(mod, 'creole_%s_Initialize' % name, self._initialize)
     setattr(mod, 'creole_%s_Finish' % name, self._finish)

where 'mod' is the module and 'name' is the name of the module.

In the basic situation, where the instance is created in the same module 
as the class, I can figure out 'mod' and 'name' like::

     cls = type(self)
     name = cls.__module__
     mod = __import__(cls.__module__)

However, this fails whenever the instance is not created in the same 
module as the class was defined (e.g. when I've factored a common base 
class into another module, and only imported this class to do steps (2) 
and (3)).  How can I figure out 'name' if the class was created in a 
different module?

One option, of course, is to pass it explicitly, e.g.::

     import C
     instance = C(__name__, ...)

This isn't a horrible option, but it does mean that I'm not hiding all 
of the step (3) machinery anymore

Another option would be to declare a dummy class, e.g.::

     import C
     class Dummy(C):
         pass
     instance = Dummy(...)

Again, this isn't horrible, but it also fails to hide some of the step 
(3) machinery.

Any other possibilities?

STeVe



More information about the Python-list mailing list