]> granicus.if.org Git - python/commitdiff
Add explicit example on how to import a submodule of a package using
authorGuido van Rossum <guido@python.org>
Fri, 4 Dec 1998 15:32:17 +0000 (15:32 +0000)
committerGuido van Rossum <guido@python.org>
Fri, 4 Dec 1998 15:32:17 +0000 (15:32 +0000)
__import__ and getattr().

Doc/lib/libfuncs.tex

index d7ee837063f0236f01981b1b658edf6dd8189654..466351d18354721773e46a43546dc0c9b185067e 100644 (file)
@@ -44,6 +44,21 @@ using \samp{import spam.ham.eggs}, the top-level package \code{spam}
 must be placed in the importing namespace, but when using \samp{from
 spam.ham import eggs}, the \code{spam.ham} subpackage must be used to
 find the \code{eggs} variable.
+As a workaround for this behavior, use \function{getattr()} to extract
+the desired components.  For example, you could define the following
+helper:
+
+\begin{verbatim}
+import string
+
+def my_import(name):
+    mod = __import__(name)
+    components = string.split(name, '.')
+    for comp in components[1:]:
+        mod = getattr(mod, comp)
+    return mod
+\end{verbatim}
+
 \end{funcdesc}
 
 \begin{funcdesc}{abs}{x}