Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #11357

Re: Relative import from script with same name as package

From "OKB (not okblacke)" <brenNOSPAMbarn@NObrenSPAMbarn.net>
Newsgroups comp.lang.python
Subject Re: Relative import from script with same name as package
Date 2011-08-13 23:55 +0000
Organization A noiseless patient Spider
Message-ID <Xns9F40ABFFADCF6OKB@88.198.244.100> (permalink)
References <Xns9F4094E80B476OKB@88.198.244.100>

Show all headers | View raw


OKB (not okblacke) wrote:

>          But why?  That __future__ import is supposed to make
>          absolute 
> imports the default, so why is "import thetest" importing
> thetest.py instead of the package called thetest?  The absolute
> import should make it look in sys.path first and not try to import
> from the script directory, right?
> 
>          If I change the outer directory name and change the code
>          in 
> thetest.py to match, it works fine.  But I shouldn't have to do
> this.  How can I get relative imports to work correctly when
> running a script whose filename is the same as that of the
> directory (and thus the package) in which it resides?

    	After a bit more googling I discovered the answer here: 
http://stackoverflow.com/questions/1959188/absolute-import-failing-in-
subpackage-that-shadows-a-stdlib-package-name

    	The deal is that sys.path by default has the empty string as the 
first element, which tells Python to look first in the directory of the 
script being executed.  This is unfortunate, but can worked around this 
way:

import sys
sys.path = sys.path[1:] + ['']

(That is, move the current directory to the end of the search path 
instead of the beginning.)

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
	--author unknown

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Relative import from script with same name as package "OKB (not okblacke)" <brenNOSPAMbarn@NObrenSPAMbarn.net> - 2011-08-13 21:39 +0000
  Re: Relative import from script with same name as package "OKB (not okblacke)" <brenNOSPAMbarn@NObrenSPAMbarn.net> - 2011-08-13 23:55 +0000
    Re: Relative import from script with same name as package Chris Angelico <rosuav@gmail.com> - 2011-08-14 01:07 +0100
  Re: Relative import from script with same name as package Oktay Şafak <oktaysafak@superonline.com> - 2011-08-14 12:57 +0300
    Re: Relative import from script with same name as package "OKB (not okblacke)" <brenNOSPAMbarn@NObrenSPAMbarn.net> - 2011-08-14 18:48 +0000
      Re: Relative import from script with same name as package Oktay Şafak <oktaysafak@superonline.com> - 2011-08-15 01:56 +0300

csiph-web