Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Importing from a Module Whose Name Is Determined at Runtime

Credit: Jürgen Hermann

Problem

You need to import a name from a module, such as from module import name, but module and name are runtime-computed expressions. This need often arises, for example when you want to support user-written plug-ins.

Solution

The _ _import_ _ built-in function allows this:

def importName(modulename, name):
    """ Import a named object from a module in the context of this function.
    """
    try:
        module = _ _import_ _(modulename, globals(), locals(  ), [name])
    except ImportError:
        return None
    return vars(module)[name]

Discussion

This recipe’s function lets you perform the equivalent of from module import name, in which either or both module and name are dynamic values (i.e., expressions or variables) rather than constant strings. For example, this can be used to implement a plug-in mechanism to extend an application with external modules that adhere to a common interface. Some programmers’ instinctive reaction to this task would be to use exec, but this instinct would be a pretty bad one. The exec statement is a last-ditch measure, to be used only when nothing else is available (which is basically never). It’s just too easy to have horrid bugs and/or security weaknesses where exec is used. In almost all cases, there are better ways. This recipe shows one such way for an important problem.

For example, suppose you have in the MyApp/extensions/spam.py file:

class Handler: def handleSomething(self): print "spam!" ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata