Two import questions in Python 3.0

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Jan 24 09:21:20 CET 2009


En Sat, 24 Jan 2009 05:24:15 -0200, Kay Schluehr <kay.schluehr at gmx.net>  
escribió:

> 1. I'd expected that absolute imports are used in Python 3.0 by
> default. I may be wrong. I've written two versions of a module
> sucks.py
>
> sucks.py
> -------------
> print ("import from lib.sucks")
>
> sucks.py
> -------------
> print ("import from package.sucks")
>
> The first is placed in the lib directory that is globally visible by
> means of PYTHONPATH. The second one is placed in a package
>
> package/
>      __init__.py
>      sucks.py
>      A.py
>
> The package also contains a module A.py defined by
>
> A.py
> ------
> import sucks
>
> Running A yields "import from package.sucks" which means unconditional
> relative import. It shadows the globally visible sucks.py module. I've
> expected it the other way round.

If you run A.py as a script, it does not "know" it lives inside a package.  
You must *import* A for it to become aware of the package.
Also, the directory containing the script comes earlier than PYTHONPATH  
entries in sys.path -- so watch for that case too.

>     python test_parser.py
>     Traceback (most recent call last):
>     File "test_parser.py", line 12, in <module>
>        from . import support
>     ValueError: Attempted relative import in non-package
>
> The standard error of the years to come that makes working with Python
> harder and reminds me that it is not a scripting language anymore
> because you can't run anything as a script not even a test.

I always consider that packages are libraries. Application code "uses" a  
library (by importing things from it). Test code should mimic closely that  
behavior: my tests always import the package, like the application would  
do.

Anyway I should revisit the strategy, I've not evaluated yet how much is  
affected by absolute imports and other changes in 3.0

-- 
Gabriel Genellina




More information about the Python-list mailing list