module import questions and question about pytest and module imports

Dave Angel davea at davea.name
Mon Dec 8 08:16:53 EST 2014


On 12/07/2014 11:50 AM, sam pendleton wrote:
> Thanks for getting back with me!
>
> On Sun, Dec 7, 2014 at 11:26 AM, Dave Angel <davea at davea.name> wrote:
>> On 12/05/2014 11:50 PM, sam pendleton wrote:
>>>
>>> garage/
>>>       |- __init__.py
>>>       |- cars/
>>>           |- __init__.py
>>>           |- hummer.py
>>> tests/
>>>       |- test_cars.py
>>>
>>> at the top of test_cars.py, there is this:
>>>       from garage.cars import hummer
>>>
>>> pytest is on this import statement, so i guess it's incorrect.
>>
>>
>> No idea what that statement is trying to say.
>
> Sorry Dave, I was saying that pytest is hung up there stating it can't
> import that module.

Why don't you just try running the module, and post the stacktrace when 
it gets an exception?  I've never used pytest, and don't know why it 
would hang on any particular line.

>
>
>> If you're going to import something, it either has to be on the sys.path, or
>> in the current directory.  Is garage/ on your sys.path?
>>
>> You can examine sys.path  by
>>     import sys
>>     print(sys.path)
>
> Having to put the garage package on the sys.path seems a little off,
> why wouldn't relative imports work?
>
> Do most people somehow put their packages in sys.path when bundling
> their python packages up to be shared with setuptools or other python
> package managers? If so, how?
>

When you get to the point of bulding a distribution, you'll be putting 
your packages in the dist_packages directory, which is on sys.path. 
However, generally your distribution utility will handle those details.

In the meantime, you can set some environment variable to add locally to 
your sys.path.

As for relative import versus other choices, that varies between Python 
2.x and 3.x, and you haven't specified exactly what Python version 
you're running or what OS you're on.

In Python 2.x, relative import was considered to be ambiguous, and 
people figured it had to change.  You might want to read

https://docs.python.org/2.5/whatsnew/pep-328.html


-- 
-- 
DaveA



More information about the Python-list mailing list