Using __import__ to access a local module attribute
jtk at yahoo.com
Mon Sep 30 16:15:17 EDT 2002
I'm trying to use __import__ to dynamically import a module in a customized
Zope 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()
just 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())
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?
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 getattr 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.
More information about the Python-list