[Tutor] import aliases ?

Kent Johnson kent37 at tds.net
Tue May 26 12:52:26 CEST 2009


On Tue, May 26, 2009 at 4:11 AM, spir <denis.spir at free.fr> wrote:
> Hello,
>
> In the case of such a dir structure:
>
> /pack
>   __init__.py
>   (modules)
>   /pack1
>      __init__.py
>      modules
>
> are the following imports synonyms:
> 1-   import pack.pack1
> 2-   from pack import pack1
> ?
>
> If yes, is there a reason for this?
>
> Also, there is something I find weird:
>
> * Using idiom 1, pack1 is only known as the compound name "pack.pack1": I cannot eg "print pack1". Consistently, to import a module, I need "from pack.pack1 import mod".
>
> * Using idiom 2, pack1 is known as "pack1" alone: I can "print pack1", which outputs "<module 'pack.pack1' from '/home/spir/prog/python/pack/pack1/__init__.pyc'>".

That is the difference between the two styles of import - the name
under which the module is imported.

> But for further imports, I still need to use the compound name "pack.pack1": "from pack1 import mod" raises "ImportError: No module named pack1", while python has just accepted to print pack1!

Yes. The import statement is not taking a module as the first
argument, it takes a name. For example in 'from pack import pack1',
'pack' does not have to be a name that is currently in scope.

Kent


More information about the Tutor mailing list