zwol: ((mad) science)
[personal profile] zwol

In Python >= 2.5, if you need to do

    from . import module

but you don't know the name of module until runtime, this is how you do it:

    mod = getattr(__import__('', globals(), locals(),
                             [name], 1), name)

(This is going on my big list of things I will change when I am the BDFL.)

Date: 2009-12-23 04:17 pm (UTC)
From: [identity profile] rezendi.livejournal.com
Huh. Interesting.

Date: 2009-12-23 05:14 pm (UTC)
From: [identity profile] zwol.livejournal.com
I'm being a little unfair. __import__ is a low-level hook function, designed to be overridden by libraries that need to modify the module search algorithm; its signature matches the needs of the internals, and it doesn't do all the work. The problem from a language design standpoint is there's no higher-level API to use for a dynamic import. This could be fixed with a stdlib module, but nobody seems to have bothered to write one.

Date: 2009-12-25 02:05 am (UTC)
From: [identity profile] zwol.livejournal.com
I suppose that might, in a few years, answer the complaint.

They need to work on the dox, though. The 3.1 importlib page make it sound like yet another bag of utilities for people writing import hooks rather than the place to look for a high level __import__ wrapper. And why do I have to specify the reference point for relative imports? Doesn't that defeat the purpose?

April 2017

S M T W T F S
      1
2345678
9101112131415
16171819 202122
23242526272829
30      

Style Credit

Expand Cut Tags

No cut tags
Page generated Jan. 10th, 2026 08:33 am
Powered by Dreamwidth Studios