Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pylint: Relative import should be

Tags:

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

like image 954
pistacchio Avatar asked May 04 '12 07:05

pistacchio


People also ask

What is relative imports?

A relative import specifies the resource to be imported relative to the current location—that is, the location where the import statement is. There are two types of relative imports: implicit and explicit.

When to use relative imports Python?

Because there, they want to make sure that other developers could also get the full path of the import module. Relative imports are helpful when you are working alone on a Python project, or the module is in the same directory where you are importing the module.

What is absolute import in Python?

In other words, it prevents you from accidentally overshadowing parts of the Python standard library by creating directories on sys. path of the same name, similar to the way naming a variable list overshadows the built-in list function. – Two-Bit Alchemist.


2 Answers

Python 2.5 introduces relative imports. They allow you to do

from .entity import Entity
like image 184
glglgl Avatar answered Oct 19 '22 04:10

glglgl


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.

like image 33
sthenault Avatar answered Oct 19 '22 03:10

sthenault