[Python-Dev] Relative import

Boris Boutillier Boris.Boutillier at arteris.net
Wed Dec 17 11:13:19 EST 2003


Just to give you a practical example, we are using python for internal 
tools in the electronic Company I'm working for.
I needed to have a non ambiguous file lookup when using import ( We set 
external dependencies for the flow when opening a file, so you can't use 
a 'if this file exist' check, when opening a file, it must always exists)
I made a special import function, that was looking for a prefix to the 
package name:
import loc.dotted.name
import glb.dotted.name
import __.dotted.name
import std.dotted.name
import xxx.dotted.name -> raise an error

"loc", look in the current directory of the module (looking to his 
__file__ attribute)
"__ "look to the parent directory
"glb" look at the root of the user working repository ( a builtins set 
before anything else is done , users don't call python they the program 
myPython )
"std" look outside the database ( in the python installation dir mainly) 
and set back the old import behaviour to ensure that import inside 
standard modules don't fail )

I know the loc,glb __ and std names are no good for a general case as 
modules can have these names, but this is just to give you an actual use 
of these relatives imports.

Boris

Nick Coghlan wrote:

> Greg Ewing wrote:
>
>> So I think we really want *three* kinds of module reference:
>>
>>    A: Explicitly absolute
>>    B: Explicitly relative to the current module
>>    C: Searched for upwards in the package hierarchy from the current
>>       module
>>
>> (Note that C is a generalisation of the current "ambiguous"
>> references which only look in two places.)
>>
>
> Alternate spellings (plus category D, which is "Python 2.3 semantics"):
>
> A: from __absolute__.dotted.name import foo
> B: from __relative__.dotted.name import bar
> C: from __heirarchy__.dotted.name import foobar
> D: from dotted.name import barfoo
>
> I believe this spelling would only require import to handle the 
> special cases as the first 'package' name (although having the 
> compiler recognise them may be a later optimisation), and should also 
> work with straight "import __absolute__.dotted.name.foo" statements.
>
> Then Guido's migration plan would apply to the progression of the D 
> semantics from the Python 2.3 model to being a shorthand for the 
> absolute semantics.
>
> And once _that_ has happened, then we could get rid of the 
> '__absolute__' version in the name of TOOWTDI.
>
> Regards,
> Nick.
>





More information about the Python-Dev mailing list