Proposal: Inline Import

Mike Meyer mwm at
Sat Dec 10 19:14:31 CET 2005

Shane Hathaway <shane at> writes:
> Let me fully elaborate the heresy I'm suggesting: I am talking about
> inline imports on every other line of code.  The obvious
> implementation would drop performance by a double digit percentage.

No, it wouldn't. The semantics of import pretty much require that the
drop in performance would most likely be negligible.

>> And your proposal is doing the import anyway, just under the
>> hood. How will you avoid the same penalty?
> The more complex implementation, which I suggested in the first
> message, is to maintain a per-module dictionary of imported objects
> (distinct from the global namespace.)  This would make inline imports
> have almost exactly the same runtime cost as a global namespace lookup.

If you put an import near every reference to a module, then each
import would "have almost exactly the same runtime cost as a global
namespace lookup." Your per-module dictionary of imported object
doesn't represent a significant improvement in module lookup time.
The extra cost comes from having to look up the module in the
namespace after you import it. However, the actual import has at most
the same runtime cost as looking up the module name, and may cost
noticably less. These costs will be swamped by the lookup cost for
non-module symbols in most code. If looking up some symbols is a
noticable part of your run-time the standard fix is to bind the
objects you are finding into your local namespace. Import already
allows this, with "from foo import bar". That will make references to
the name run as much fater than your proposed inline import than it
runs faster than doing an import before every line that references a

In summary, the performance hit from doing many imports may be
significant compared to the cost only doing one import, but that still
represents only a small fraction of the total runtime of most code. In
the cases where that isn't the case, we already have a solution
available with better performance than any of the previously discussed


Mike Meyer <mwm at>
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

More information about the Python-list mailing list