[Tutor] Dynamic inheritance?
kent37 at tds.net
Wed Nov 23 14:05:34 CET 2005
Jan Eden wrote:
> Jan Eden wrote on 22.11.2005:
>>Kent Johnson wrote on 20.11.2005:
>>>Use getattr() to access attributes by name. SiteA is an attribute
>>>of Templates and Page is an attribute of SiteA so you can get use
>>>getattr() twice to get what you want:
>>>site = getattr(Templates, self.site_name) self.template =
>>Unfortunately, this does not seem to work if Templates is a package,
>>not a module. Python complains:
>>AttributeError: 'module' object has no attribute 'SiteA'
>> args = ("'module' object has no attribute 'SiteA'",)
>>even though there is a module SiteA within package Templates. When
>>manually importing SiteA from Templates, everything is good.
> Found a solution:
> import Templates
> def GetTemplates(self):
> __import__('Templates.', globals(), locals(), [self.identifier])
> site = getattr(Templates, self.identifier)
> self.template = getattr(site, self.template_type)
Sorry about the bad advice. There is something about packages I don't fully understand - the modules in a package are not available as attributes in the package until the submodules have been imported. For example, using the standard email package as an example, if just email is imported then the submodules are not available as attributes:
>>> import email
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'module' object has no attribute 'Charset'
If I explicitly import the sub-module then it becomes available as an attribute:
>>> from email import Charset
<module 'email.Charset' from 'C:\Python24\lib\email\Charset.pyc'>
Your __import__() statement is doing the same magic as the explicit 'from email import Charset'.
The thing that confuses me about this is that for some modules the extra import is not needed. For example:
>>> import os
>>> getattr(os, 'path')
<module 'ntpath' from 'C:\Python24\lib\ntpath.pyc'>
OK looking at os.py, it is actually not a package, it is a module that imports other modules as attributes. It just looks like a package from the outside. So maybe os is the only strange one.
More information about the Tutor