Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-2710

The first argument to class methods should follow the naming convention

    XMLWordPrintable

    Details

    • Message:
      Rename XXX to a valid class parameter name or add the missing class parameter.
    • Highlighting:
      Hide

      The first parameter of the class method.

      Show
      The first parameter of the class method.
    • List of parameters:
      Hide

      key : classParameterNames
      Description: Comma separated list of accepted values for a class parameter.
      Default value : cls,mcs
      Type: string

      Show
      key : classParameterNames Description: Comma separated list of accepted values for a class parameter. Default value : cls,mcs Type: string
    • Default Severity:
      Critical
    • Impact:
      High
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Python
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      5min

      Description

      By convention, the first argument to class methods, i.e. methods decorated with @classmethod, is named cls as a representation and a reminder that the argument is the class itself. Name the argument something else, and you stand a good chance of confusing both users and maintainers of the code. It might also indicate that the cls parameter was forgotten, in which case calling the method will most probably fail. This rule also applies to methods __init_subclass__, __class_getitem__ and __new__ as their first argument is always the class instead of "self".

      By default this rule accepts cls and mcs, which is sometime used in metaclasses, as valid names for class parameters. You can set your own list of accepted names via the parameter classParameterNames.

      This rule raises an issue when the first parameter of a class method is not an accepted name.

      Noncompliant Code Example

      class Rectangle(object):
      
        @classmethod
        def area(bob, height, width):  #Noncompliant
          return height * width
      

      Compliant Solution

      class Rectangle(object):
      
        @classmethod
        def area(cls, height, width):
          return height * width
      

      See

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              ann.campbell.2 Ann Campbell
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated: