restricting import to current package

Robert Roy rjroy at takingcontrol.com
Sat Oct 7 09:24:01 EDT 2000


On Fri, 6 Oct 2000 09:40:08 -0500, "Jeff Kunce"
<kuncej at mail.conservation.state.mo.us> wrote:

>> >Is there a way to do something like:
>> >   from . import mymodule
>> >In other words:
>> >  try to import mymodule from the same package (or directory) as this
>module
>> >  If mymodule is not there, raise ImportError
>> >
>> import mymodule
>> see the tutorial on intrapackage references
>
>Not really. That will look *first* in the current package, but then will
>go merrily down sys.path looking for any other mymodule it can find.
>
>When you say:
>      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.


It might  be possible to do something like this though,

import os
import mymodule
if os.path.split(mymodule.__file__)[0] != os.path.split(__file__)[0]:
	raise ImportError


This should work as long as the module is not the __main__ module or
the module you are importing is not a builtin (eg cPickle). In those
cases there is no __file__ variable defined and you would get an
AttributeError.  You could always wrap the above in a try statement...
And it gets complicated in a hurry lol... Would be nice if there was a
__package__ magic variable...


Bob




More information about the Python-list mailing list