Import question

Alex Martelli aleaxit at yahoo.com
Sun May 20 04:06:48 EDT 2001


"Costas Menico" <costas at meezon.com> wrote in message
news:3b06c980.4101997 at News.CIS.DFN.DE...
> I find it annoying to force my code to be imported only from sys.path.
> Is there a way to import code from any path without having to add it
> to sys.path?

Sure!  Built-in module imp gives you all the bricks you need for
the purpose of building this particular outhouse:-).


> e.g. Why can't we do import c:\\myapppath\\myutil and then that would
> make myutil be loaded.

...under what name?  If just undecorated 'myutil', this runs into
potential conflicts.  What happens if your module a.py has:

    import c:\\fora\\peep

and your module b.py has

    import c:\\forb\\peep

WHICH one of the two modules, if either, becomes the one
referred to by sys.modules['peep']?  The potential for deep
ambiguity seems large to me, and Python's strategy when no
obvious strategy exists to resolve the ambiguity is generally
to NOT guess, but rather force explicit specification.

An advanced Python programmer will easily build a custom
import strategy for those exceedingly rare cases where the
obvious approach of altering sys.path is not desired.  A less
advanced user is best not encouraged to hardwire module
paths in his or her source code, not a very good practice.

Note that a reasonably common retort when somebody asks
for a built-in functionality X and is reminded that X is easy
to build with existing bricks is "but if X is not standard I
can't easily use it in my programs intended for distribution".
Quite apart from the issue of the general merit of this stance,
it clearly doesn't apply here -- programs intended for such
distribution would be PARTICULARLY wise to avoid having
any hard-coded absolute path:-).


Alex






More information about the Python-list mailing list