[Zope] Using __import__ in python product to access a local module attribute

Jeff Kowalczyk jtk@yahoo.com
Mon, 30 Sep 2002 11:58:35 -0400


I'm trying to use __import__ to dynamically import a module in a customized
formulator python product, and thereby access a singleton instance attribute
of the primary class wtih a call to getattr. I can get it to work with
hardcoding the module name, but I don't see what I'm missing when I try to
use __import__. The code below is just an early version of a means to an
end, and I'm wide open to better ways accessing the instance attribute.
Metaprogramming babysteps, I guess...

The MyExtClassInstance attribute in MyExtModule.py that I'm trying to access
is defined like this:
MyExtClassInstance = MyExtClass()

justl like the widget and validator formulator classes are. MyExtModule.py
is in the same product directory with my customized formulator filesystem
product, call it 'FormulatorMyExt'.

--- FieldRegistry.py ------------------------------------------------------
def initializeFieldForm(field_class, components=('widget','validator')):
    """ """
    from Form import BasicForm
    from DummyField import fields

    form = BasicForm()
    override_form = BasicForm()
    tales_form = BasicForm()
    for component in components:
        if component not in ('widget','validator'):
           # when the seq is ('widget','validator','myExtModule')
            import MyExtModule # This works ...
           # but what I intend is a working form of either of these next
lines....
           # __import__(component.capitalize(), globals(), locals())

#__import__(getattr(Products.FormulatorMyExt,component.capitalize()),
globals(), locals())
            setattr(field_class, component,
getattr(MyExtModule,component.capitalize()+'Instance'))

I get errors like:
NameError: global name 'Layout' is not defined (in the first case, and)
NameError: global name 'Products' is not defined (in the second case)

Does anyone see my mistakes here? __import__ isn't restricted to product
python code is it?

And obviously, I want to get that last line of hardcoded MyExtModule name
out of there, but it obfuscated the problem to add that here. I can do it
with a setattr call, I think, contingent on solving the former problem.

Thanks for any help with using __import__, including the from list, or
suggestion of a completely different way to do it as appropriate.