import unknown module name

Andrew Dalke adalke at mindspring.com
Thu Jan 9 20:13:18 EST 2003


deckerben wrote:
> I did some looking but I haven't been able to find an example how to import
> an unknown encoding from 'encodings'.

>     try:
>         pagename = "encodings." + oldpage
>         charset = __import__(pagename)
>         codepage = charset
>     except:

I think there's a utility function to get this, but I
don't know enough about the Unicode modules.

In general, __import__ returns the top-level module,
and not the submodules.  You'll need to do

   codepage = getattar(__import__(pagename), "oldpage")

Also, use "except ImportError" instead of a blanket except.

If there's more than one level, this should work (untested)

    codepage = charset
    terms = pagename.split(".")
    for term in terms[1:]:
        codepage = getattr(codepage, term)

I need this just enough to be annoying ....

					Andrew
					dalke at dalkescientific.com





More information about the Python-list mailing list