restricting import to current package

Michal Wallace sabren at manifestation.com
Sat Oct 7 09:55:15 EDT 2000


On Sat, 7 Oct 2000, Robert Roy wrote:

> On Fri, 6 Oct 2000 09:40:08 -0500, "Jeff Kunce"
> <kuncej at mail.conservation.state.mo.us> wrote:
>
> >      from mypackage import mymodule
> >python will look for mymodule *exclusively* in mypackage.
> >I want to do the same thing for the (unspecified) current package.
> >
> >  --Jeff
> >
> 
> Sorry, I misunderstood what you were trying to do. There does not seem
> to be a simple way to do what you want. You could write your own
> import handler using the imp module but that may be more effort than
> it is worth.


:) I love trouble... How's this:


def localimport(modulename):
    import sys
    oldpath = sys.path
    sys.path = ["."]

    # raise an error to get calling namespace:
    try:
        1 + None
    except:
        callingNS = sys.exc_info()[2].tb_frame.f_back

    # now import the module
    try:
        callingNS.f_locals[modulename]= \
            __import__(modulename, callingNS.f_locals, callingNS.f_globals)
        gotError = 0 
    except:
        gotError = 1
        
    sys.path = oldpath

    if gotError:
        raise ImportError, "no %s in local directory" % modulename



Of course, changing sys.path means that the module you're importing
can't import any modules that aren't in the current path, or you'll
get an error... But... ask a silly question.. :)


Cheers,

- Michal
------------------------------------------------------------------------
www.manifestation.com  www.sabren.com  www.linkwatcher.com  www.zike.net
------------------------------------------------------------------------





More information about the Python-list mailing list