pistacchio
pistacchio

Reputation: 58863

Pylint: Relative import should be

I'm checking a module with Pylint. The project has this structure:

/builder
    __init__.py
    entity.py
    product.py

Within product I import entity like this:

from entity import Entity

but Pylint laments that:

************* Module builder.product
W:  5,0: Relative import 'entity', should be 'builder.entity'

However from builder.entity import Entity doesn't recognize the package, and from ..builder.entity import Entity doesn't work either. What is Pylint complaining about? Thanks

Upvotes: 20

Views: 13554

Answers (4)

glglgl
glglgl

Reputation: 91017

Python 2.5 introduces relative imports. They allow you to do

from .entity import Entity

Upvotes: 20

sthenault
sthenault

Reputation: 15125

The __init__.py file makes pylint think your code is a package (namely "builder").

Hence when pylint see "from entity import Entity", it detects it properly as an implicit relative import (you can do explicit relative import using '.' since python 2.6, as other posters have advertised) and reports it.

Then, if "from builder.entity import Entity" doesn't work, it's a PYTHONPATH pb : ensure the directory containing the "builder" directory is in your PYTHONPATH (an alternative pb being proposed by gurney alex). Unless you didn't intended to write a package, then removing the __init__.py is probably the way to go.

Upvotes: 10

gurney alex
gurney alex

Reputation: 13645

What do you get if you include the following lines at the top of product.py:

import builder
print builder

My guess is that you are importing a different module / package builder from some place in your PYTHONPATH which is before what you're using.

Upvotes: 0

Sebastian Dahlgren
Sebastian Dahlgren

Reputation: 967

glglgl's answer is correct if you have a newer Python version.

However if you don't you must just make sure that the package you are validating is in your PYTHONPATH. See the examples below.

[sebastian ~/tmp/testpy]$ pylint -r n a.py 
************* Module a
C:  1: Missing docstring
F:  1: Unable to import 'testpy.b'
[sebastian ~/tmp/testpy]$ PYTHONPATH=".." pylint -r n a.py 
************* Module a
C:  1: Missing docstring

Upvotes: -1

Related Questions