Search code examples
pythonpylint

Ignore a specific builtin "id" using Pylint - Python


I would like to allow to redefine id as an attribute in a generic class. Pylint catches this error as: bam_sdk\core_element.py:7:44: W0622: Redefining built-in 'id' (redefined-builtin) I would like to allow "id" to be overwritten, however not other builtin's like "int, str etc.".

Is there a way to only disable this specific error for only this specific value "id"?

from typing import Optional


class Element:
    counter = 1

    def __init__(self, name: Optional[str], id: Optional[int]) -> None:
        self.id = id if id else self.__class__.counter
        self.name = name if name else f"{self.__class__.__name__}-{self.id}"
        self.__class__.counter += 1

Solution

  • It's not the attribute it's complaining about; it's the parameter name. The standard convention is to append a _ to the name to avoid the shadowing.

    def __init__(self, name: Optional[str], id_: Optional[int]) -> None:
        self.id = id_ if id_ else self.__class__.counter
        self.name = name if name else f"{self.__class__.__name__}-{self.id}"
        self.__class__.counter += 1
    

    I find it slightly cleaner to modify the value of the parameter rather than using a conditional expression.

    def __init__(self, name: Optional[str], id_: Optional[int]) -> None:
        if id_ is None:
            id_ = self.__class__.counter
    
        if name is None:
            name = f"{self.__class__.__name__}-{id_}"
    
        self.id = id_
        self.name = name
        self.__class__.counter += 1