Usual practice: running/testing modules in a package

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Aug 18 08:28:43 EDT 2008


En Wed, 13 Aug 2008 04:57:32 -0300, alito <alitosis at gmail.com> escribió:

> Hi all,
>
> I am new to using packages to group my modules.  I can't figure out
> how to run a module that uses relative imports without writing a
> wrapper that imports that module.  Everything I try it complains that
> I am attempting a relative import in a non-package.
>
> eg
> ~/python/testpackage$ ls
> config.py  importer.py  __init__.py
>
> ~/python/testpackage$ cat importer.py
> from . import config
> config.hello()
>
> ~/python/testpackage$ cat config.py
> def hello():
> 	print 'hello'
>
> __init__.py is empty
>
> ~/python/testpackage$ python importer.py
> Traceback (most recent call last):
>   File "importer.py", line 1, in <module>
>     from . import config
> ValueError: Attempted relative import in non-package
>
> [...more attempts...]
>
> So, how do I run these modules without writing a wrapper script for
> each one?  My main use actually would be to get pylint to analyse
> them, but it seems to use the python import system, so it fails
> whenever python fails.  If anyone can tell me how to get pychecker to
> even be able to use a wrapper, it would also be very beneficial.

A package is a library, meant to be imported by some other code. Your main script (or the testing code) is a program, it uses (i.e. imports) the library.
I usually put the test code or the main entry point one level above the package in the development environment. This way, "import testpackage" works almost the same as it would in the production environment (where the package is installed, probably in site-packages)

-- 
Gabriel Genellina




More information about the Python-list mailing list