SonarSource Rules
  • Products

    In-IDE

    Code Quality and Security in your IDE with SonarQube Ide

    IDE extension that lets you fix coding issues before they exist!

    Discover SonarQube for IDE

    SaaS

    Code Quality and Security in the cloud with SonarQube Cloud

    Setup is effortless and analysis is automatic for most languages

    Discover SonarQube Cloud

    Self-Hosted

    Code Quality and Security Self-Hosted with SonarQube Server

    Fast, accurate analysis; enterprise scalability

    Discover SonarQube Server
  • SecretsSecrets
  • ABAPABAP
  • AnsibleAnsible
  • ApexApex
  • AzureResourceManagerAzureResourceManager
  • CC
  • C#C#
  • C++C++
  • CloudFormationCloudFormation
  • COBOLCOBOL
  • CSSCSS
  • DartDart
  • DockerDocker
  • FlexFlex
  • GitHub ActionsGitHub Actions
  • GoGo
  • GroovyGroovy
  • HTMLHTML
  • JavaJava
  • JavaScriptJavaScript
  • JSONJSON
  • JCLJCL
  • KotlinKotlin
  • KubernetesKubernetes
  • Objective CObjective C
  • PHPPHP
  • PL/IPL/I
  • PL/SQLPL/SQL
  • PythonPython
  • RPGRPG
  • RubyRuby
  • RustRust
  • ScalaScala
  • ShellShell
  • SwiftSwift
  • TerraformTerraform
  • TextText
  • TypeScriptTypeScript
  • T-SQLT-SQL
  • VB.NETVB.NET
  • VB6VB6
  • XMLXML
  • YAMLYAML
Python

Python static code analysis

Unique rules to find Bugs, Vulnerabilities, Security Hotspots, and Code Smells in your PYTHON code

  • All rules 414
  • Vulnerability45
  • Bug104
  • Security Hotspot50
  • Code Smell215

  • Quick Fix 33
 
Tags
    Impact
      Clean code attribute
        1. Template string processing should use structural pattern matching

           Code Smell
        2. Compression modules should be imported from the compression namespace

           Code Smell
        3. Tensor operations should rely on automatic broadcasting instead of manual expansion

           Code Smell
        4. Use "torch.empty()" instead of list comprehensions for empty tensor initialization

           Code Smell
        5. Tensors should not be concatenated incrementally in loops

           Code Smell
        6. Use PyTorch Lightning's built-in checkpointing instead of manual checkpoint saving

           Code Smell
        7. PyTorch module classes should not be instantiated inline in forward methods

           Code Smell
        8. Specify "start_dim" when using "torch.flatten" to preserve batch dimension

           Code Smell
        9. Tensor copying should use recommended methods

           Code Smell
        10. Issue suppression comment should have the correct format

           Code Smell
        11. boto3 operations that support pagination should be performed using paginators or manual pagination handling

           Code Smell
        12. AWS waiters should be used instead of custom polling loops

           Code Smell
        13. "botocore.exceptions.ClientError" should be explicitly caught and handled

           Code Smell
        14. Reserved environment variable names should not be overridden in Lambda functions

           Code Smell
        15. Numerically stable PyTorch functions should be used instead of their unstable equivalents

           Code Smell
        16. AWS Lambda handlers must not be an async function

           Code Smell
        17. AWS CloudWatch metrics namespace should not begin with `AWS/`

           Code Smell
        18. Populating a dictionary with a constant value should be done with dict.fromkeys() method call

           Code Smell
        19. Iteration over a dictionary key value pairs should be done with the items() method call

           Code Smell
        20. "sorted" should not be wrapped directly inside "set"

           Code Smell
        21. TaskGroup/Nursery should not be used for a single start call

           Code Smell
        22. Using ".items()" to iterate over a dictionary should be avoided if possible.

           Code Smell
        23. Passing a reversed iterable to "set()", "sorted()", or "reversed()" should be avoided

           Code Smell
        24. The "sorted" function call should not be passed to the "reversed" function as an argument

           Code Smell
        25. Redundant collection functions should be avoided

           Code Smell
        26. "defaultdict" should not be initialized with "default_factory" as a keyword argument

           Code Smell
        27. Dictionary comprehension should not use a static key

           Code Smell
        28. Generators and comprehensions should be preferred over the usage of "map" and "lambda" when creating collection

           Code Smell
        29. When iterating over an iterable object, using "list()" should be avoided

           Code Smell
        30. Async functions should use async features

           Code Smell
        31. Comprehensions only used to copy should be replaced with the respective constructor calls

           Code Smell
        32. Literal syntax should be preferred when creating empty collections or dictionaries with keyword arguments

           Code Smell
        33. Creation of collections with literals or comprehensions should not be wrapped in type constructors

           Code Smell
        34. Comprehensions should be used instead of constructors around generator expressions

           Code Smell
        35. List comprehensions should not be used with "any()" or "all()"

           Code Smell
        36. Checkpoints should be used instead of sleep(0)

           Code Smell
        37. Long sleep durations should use sleep_forever() instead of arbitrary intervals

           Code Smell
        38. Events should be used instead of `sleep` in asynchronous loops

           Code Smell
        39. Asynchronous functions should not accept timeout parameters

           Code Smell
        40. "master" and "appName" should be set when constructing PySpark "SparkContext"s and "SparkSession"s

           Code Smell
        41. PySpark's "RDD.groupByKey", when used in conjunction with "RDD.mapValues" with a commutative and associative operation, should be replaced by "RDD.reduceByKey"

           Code Smell
        42. PySpark's "DataFrame" column names should be unique

           Code Smell
        43. PySpark "dropDuplicates" subset argument should not be provided with an empty list

           Code Smell
        44. Complex logic provided to PySpark "withColumn", "filter" and "when" methods should be refactored into separate expressions

           Code Smell
        45. PySpark lit(None) should be used when populating empty columns

           Code Smell
        46. PySpark DataFrame toPandas function should be avoided

           Code Smell
        47. The "how" parameter should be specified when joining two PySpark DataFrames

           Code Smell
        48. "withColumns" method should be preferred over "withColumn" when multiple columns are specified

           Code Smell
        49. PySpark DataFrames used multiple times should be cached or persisted

           Code Smell
        50. PySpark Pandas DataFrame columns should not use a reserved name

           Code Smell
        51. The "subset" argument should be provided when using PySpark DataFrame "dropDuplicates" method

           Code Smell
        52. PySpark Window functions should always specify a frame

           Code Smell
        53. The "num_workers" parameter should be specified for "torch.utils.data.DataLoader"

           Code Smell
        54. "model.eval()" or "model.train()" should be called after loading the state of a PyTorch model

           Code Smell
        55. "torch.tensor" should be used instead of "torch.autograd.Variable"

           Code Smell
        56. Subclasses of Scikit-Learn's "BaseEstimator" should not set attributes ending with "_" in the "__init__" method

           Code Smell
        57. Important hyperparameters should be specified for machine learning libraries' estimators and optimizers

           Code Smell
        58. Nested estimator parameters modification in a Pipeline should refer to valid parameters

           Code Smell
        59. "memory" parameter should be specified for Scikit-Learn Pipeline

           Code Smell
        60. The reduction axis/dimension should be specified when using reduction operations

           Code Smell
        61. Python side effects should not be used inside a "tf.function"

           Code Smell
        62. The "validate_indices" argument should not be set for "tf.gather" function call

           Code Smell
        63. The "input_shape" parameter should not be specified for "tf.keras.Model" subclasses

           Code Smell
        64. "tf.Variable" objects should be singletons when created inside of a "tf.function"

           Code Smell
        65. "tf.function" should not depend on global or free Python variables

           Code Smell
        66. "tensorflow.function" should not be recursive

           Code Smell
        67. Using timezone-aware "datetime" objects should be preferred over using "datetime.datetime.utcnow" and "datetime.datetime.utcfromtimestamp"

           Code Smell
        68. Numpy weekmask should have a valid value

           Code Smell
        69. Dates should be formatted correctly when using "pandas.to_datetime" with "dayfirst" or "yearfirst" arguments

           Code Smell
        70. "zoneinfo" should be preferred to "pytz" when using Python 3.9 and later

           Code Smell
        71. "pytz.timezone" should not be passed to the "datetime.datetime" constructor

           Code Smell
        72. The 12-hour format should be used with the AM/PM marker, otherwise the 24-hour format should be used

           Code Smell
        73. Constructor attributes of date and time objects should be in the range of possible values

           Code Smell
        74. "f-strings" should not be nested too deeply

           Code Smell
        75. Generic functions should be defined using the type parameter syntax

           Code Smell
        76. Generic type statements should not use "TypeVars"

           Code Smell
        77. Type aliases should be declared with a "type" statement

           Code Smell
        78. Generic classes should be defined using the type parameter syntax

           Code Smell
        79. pandas.pipe method should be preferred over long chains of instructions

           Code Smell
        80. The "pandas.DataFrame.to_numpy()" method should be preferred to the "pandas.DataFrame.values" attribute

           Code Smell
        81. 'dtype' parameter should be provided when using 'pandas.read_csv' or 'pandas.read_table'

           Code Smell
        82. When using pandas.merge or pandas.join, the parameters on, how and validate should be provided

           Code Smell
        83. inplace=True should not be used when modifying a Pandas DataFrame

           Code Smell
        84. Deprecated NumPy aliases of built-in types should not be used

           Code Smell
        85. np.nonzero should be preferred over np.where when only the condition parameter is set

           Code Smell
        86. Passing a list to np.array should be preferred over passing a generator

           Code Smell
        87. numpy.random.Generator should be preferred to numpy.random.RandomState

           Code Smell
        88. Results that depend on random number generation should be reproducible

           Code Smell
        89. Assignments of lambdas to variables should be replaced by function definitions

           Code Smell
        90. "isinstance()" should be preferred to direct type comparisons

           Code Smell
        91. 'startswith' or 'endswith' methods should be used instead of string slicing in condition expressions

           Code Smell
        92. Fields of a Django ModelFom should be defined explicitly

           Code Smell
        93. "locals()" should not be passed to a Django "render()" function

           Code Smell
        94. Django models should define a "__str__" method

           Code Smell
        95. 'null=True' should not be used on string-based fields in Django models

           Code Smell
        96. Union type expressions should be preferred over "typing.Union" in type hints

           Code Smell
        97. Built-in generic types should be preferred over the typing module in type hints

           Code Smell
        98. Type hints of generic types should specify their type parameters

           Code Smell
        99. Any should not be used as a type hint

           Code Smell
        100. Function parameters should have type hints

           Code Smell
        101. Function returns should have type hints

           Code Smell
        102. Octal escape sequences should not be used in regular expressions

           Code Smell
        103. Character classes in regular expressions should not contain only one character

           Code Smell
        104. Superfluous curly brace quantifiers should be avoided

           Code Smell
        105. Non-capturing groups without quantifier should not be used

           Code Smell
        106. Regular expression quantifiers and character classes should be used concisely

           Code Smell
        107. Regular expressions should not contain empty groups

           Code Smell
        108. Regular expressions should not contain multiple spaces

           Code Smell
        109. AWS region should not be set with a hardcoded String

           Code Smell
        110. Lambdas should not invoke other lambdas synchronously

           Code Smell
        111. Reusable resources should be initialized at construction time of Lambda functions

           Code Smell
        112. Single-character alternations in regular expressions should be replaced with character classes

           Code Smell
        113. Reluctant quantifiers in regular expressions should be followed by an expression that can't match the empty string

           Code Smell
        114. Tests should be skipped explicitly

           Code Smell
        115. Assertions should not fail or succeed unconditionally

           Code Smell
        116. The most specific "unittest" assertion should be used

           Code Smell
        117. Test methods should be discoverable

           Code Smell
        118. Values assigned to variables should match their type annotations

           Code Smell
        119. Function return types should be consistent with their type hint

           Code Smell
        120. Character classes in regular expressions should not contain the same character twice

           Code Smell
        121. Type checks shouldn't be confusing

           Code Smell
        122. Names of regular expressions named groups should be used

           Code Smell
        123. Character classes should be preferred over reluctant quantifiers in regular expressions

           Code Smell
        124. Regular expressions should not be too complicated

           Code Smell
        125. Builtins should not be shadowed by local variables

           Code Smell
        126. Implicit string and byte concatenations should not be confusing

           Code Smell
        127. Constants should not be used as conditions

           Code Smell
        128. Identity comparisons should not be used with cached types

           Code Smell
        129. Expressions creating sets should not have duplicate values

           Code Smell
        130. Expressions creating dictionaries should not have duplicate keys

           Code Smell
        131. "SystemExit" should be re-raised

           Code Smell
        132. Bare "raise" statements should only be used in "except" blocks

           Code Smell
        133. Comparison to None should not be constant

           Code Smell
        134. "self" should be the first argument to instance methods

           Code Smell
        135. Function parameters' default values should not be modified or assigned

           Code Smell
        136. A subclass should not be in the same "except" statement as a parent class

           Code Smell
        137. Some special methods should return "NotImplemented" instead of raising "NotImplementedError"

           Code Smell
        138. Custom Exception classes should inherit from "Exception" or one of its subclasses

           Code Smell
        139. Special method "__exit__" should not re-raise the provided exception

           Code Smell
        140. Bare "raise" statements should not be used in "finally" blocks

           Code Smell
        141. Walrus operator should not make code confusing

           Code Smell
        142. Arguments given to functions should be of an expected type

           Code Smell
        143. Unused scope-limited definitions should be removed

           Code Smell
        144. `str.replace` should be preferred to `re.sub`

           Code Smell
        145. Unread "private" attributes should be removed

           Code Smell
        146. Functions and methods should not have identical implementations

           Code Smell
        147. Unused private nested classes should be removed

           Code Smell
        148. Functions should use "return" consistently

           Code Smell
        149. Cognitive Complexity of functions should not be too high

           Code Smell
        150. Jump statements should not be redundant

           Code Smell
        151. Functions returns should not be invariant

           Code Smell
        152. String formatting should be used correctly

           Code Smell
        153. Conditional expressions should not be nested

           Code Smell
        154. Loops without "break" should not have "else" clauses

           Code Smell
        155. "pass" should not be used needlessly

           Code Smell
        156. Doubled prefix operators "not" and "~" should not be used

           Code Smell
        157. "except" clauses should do more than raise the same issue

           Code Smell
        158. The first argument to class methods should follow the naming convention

           Code Smell
        159. Method overrides should not change contracts

           Code Smell
        160. Boolean expressions should not be gratuitous

           Code Smell
        161. Methods and properties that don't access instance data should be static

           Code Smell
        162. The "print" statement should not be used

           Code Smell
        163. "<>" should not be used to test inequality

           Code Smell
        164. The "exec" statement should not be used

           Code Smell
        165. Backticks should not be used

           Code Smell
        166. Python parser failure

           Code Smell
        167. Wildcard imports should not be used

           Code Smell
        168. Boolean checks should not be inverted

           Code Smell
        169. Files should not be too complex

           Code Smell
        170. Two branches in a conditional structure should not have exactly the same implementation

           Code Smell
        171. Unused assignments should be removed

           Code Smell
        172. Methods and field names should not differ only by capitalization

           Code Smell
        173. New-style classes should be used

           Code Smell
        174. Parentheses should not be used after certain keywords

           Code Smell
        175. Docstrings should be defined

           Code Smell
        176. Track "TODO" and "FIXME" comments that do not contain a reference to a person

           Code Smell
        177. A field should not duplicate the name of its containing class

           Code Smell
        178. A reason should be provided when skipping a test

           Code Smell
        179. Module names should comply with a naming convention

           Code Smell
        180. Function names should comply with a naming convention

           Code Smell
        181. Cyclomatic Complexity of functions should not be too high

           Code Smell
        182. Functions and lambdas should not reference variables defined in enclosing loops

           Code Smell
        183. Unused local variables should be removed

           Code Smell
        184. Track lack of copyright and license headers

           Code Smell
        185. Comments should not be located at the end of lines of code

           Code Smell
        186. Functions should not have too many lines of code

           Code Smell
        187. Control flow statements "if", "for", "while", "try" and "with" should not be nested too deeply

           Code Smell
        188. Cyclomatic Complexity of classes should not be too high

           Code Smell
        189. Track uses of noqa comments

           Code Smell
        190. Track uses of "NOSONAR" comments

           Code Smell
        191. Sections of code should not be commented out

           Code Smell
        192. Track comments matching a regular expression

           Code Smell
        193. Statements should be on separate lines

           Code Smell
        194. String literals should not be duplicated

           Code Smell
        195. Functions and methods should not be empty

           Code Smell
        196. Unused function parameters should be removed

           Code Smell
        197. Local variable and function parameter names should comply with a naming convention

           Code Smell
        198. Field names should comply with a naming convention

           Code Smell
        199. Unused class-private methods should be removed

           Code Smell
        200. Functions should not contain too many return statements

           Code Smell
        201. Track uses of "TODO" tags

           Code Smell
        202. Track uses of "FIXME" tags

           Code Smell
        203. Lines should not end with trailing whitespaces

           Code Smell
        204. Files should end with a newline

           Code Smell
        205. Long suffix "L" should be upper case

           Code Smell
        206. Unnecessary imports should be removed

           Code Smell
        207. "Exception" and "BaseException" should not be raised

           Code Smell
        208. Redundant pairs of parentheses should be removed

           Code Smell
        209. Nested blocks of code should not be left empty

           Code Smell
        210. Functions, methods and lambdas should not have too many parameters

           Code Smell
        211. Mergeable "if" statements should be combined

           Code Smell
        212. Files should not have too many lines of code

           Code Smell
        213. Lines should not be too long

           Code Smell
        214. Class names should comply with a naming convention

           Code Smell
        215. Method names should comply with a naming convention

           Code Smell

        Tests should be skipped explicitly

        intentionality - clear
        maintainability
        Code Smell
        • tests
        • bad-practice

        Why is this an issue?

        More Info

        Test frameworks provide a mechanism to skip tests if their prerequisites are not met, by either calling dedicated methods (e.g: unittest.TestCase.skipTest, pytest.skip, …​) or using decorators (e.g: unittest.skip, pytest.mark.skip, …​)

        Using a return statement instead will make the test succeed, even though no assertion has been performed. It is therefore better to flag the test as skipped in such situation.

        This rule raises an issue when a return is performed conditionally at the beginning of a test method.

        No issue will be raised if the return is unconditional as S1763 already raises an issue in such case.

        The supported frameworks are Pytest and Unittest.

        Noncompliant code example

        import unittest
        class MyTest(unittest.TestCase):
        
            def test_something(self):
                if not external_resource_available():
                    return  # Noncompliant
                self.assertEqual(foo(), 42)
        

        Compliant solution

        import unittest
        class MyTest(unittest.TestCase):
        
            def test_something(self):
                if not external_resource_available():
                    self.skipTest("prerequisite not met")
                self.assertEqual(foo(), 42)
        
          Available In:
        • SonarQube IdeCatch issues on the fly,
          in your IDE
        • SonarQube CloudDetect issues in your GitHub, Azure DevOps Services, Bitbucket Cloud, GitLab repositories
        • SonarQube Community BuildAnalyze code in your
          on-premise CI
          Available Since
          9.7
        • SonarQube ServerAnalyze code in your
          on-premise CI
          Developer Edition
          Available Since
          9.7

        © 2026 SonarSource Sàrl. All rights reserved.

        Privacy Policy | Cookie Policy | Terms of Use