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. Functions and methods should only return expected values

           Bug
        2. The number and name of arguments passed to a function should match its parameters

           Bug
        3. Non-empty statements should change control flow or have at least one side-effect

           Bug
        4. Template string processing should use structural pattern matching

           Code Smell
        5. Template and str should not be concatenated directly

           Bug
        6. Template strings should be processed before use

           Bug
        7. Compression modules should be imported from the compression namespace

           Code Smell
        8. Return, break, or continue statements should not exit finally blocks

           Bug
        9. "NotImplemented" should not be used in boolean contexts

           Bug
        10. Tensor operations should rely on automatic broadcasting instead of manual expansion

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

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

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

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

           Code Smell
        15. Method calls should use parentheses when saving PyTorch model state

           Bug
        16. Specify "start_dim" when using "torch.flatten" to preserve batch dimension

           Code Smell
        17. AI agent code execution without sandboxing is security-sensitive

           Security Hotspot
        18. "super()" calls should not be used in TorchScript methods

           Bug
        19. Operating AI agents without predefined boundaries is security-sensitive.

           Security Hotspot
        20. Tensor copying should use recommended methods

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

           Code Smell
        22. Long-term AWS access keys should not be used directly in code

           Vulnerability
        23. boto3 operations that support pagination should be performed using paginators or manual pagination handling

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

           Code Smell
        25. AWS Lambda handlers should clean up temporary files in /tmp directory

           Bug
        26. "botocore.exceptions.ClientError" should be explicitly caught and handled

           Code Smell
        27. Network calls in AWS Lambda functions shouldn't be made without explicit timeout parameters

           Bug
        28. Reserved environment variable names should not be overridden in Lambda functions

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

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

           Code Smell
        31. AWS Lambda handlers should return only JSON serializable values

           Bug
        32. AWS CloudWatch metrics namespace should not begin with `AWS/`

           Code Smell
        33. S3 operations should verify bucket ownership using ExpectedBucketOwner parameter

           Vulnerability
        34. Populating a dictionary with a constant value should be done with dict.fromkeys() method call

           Code Smell
        35. Privileged prompts should not be vulnerable to injection attacks

           Vulnerability
        36. Iteration over a dictionary key value pairs should be done with the items() method call

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

           Code Smell
        38. "async with" should be used for asynchronous resource management

           Bug
        39. Control flow statements should not be used inside TaskGroup or Nursery blocks

           Bug
        40. TaskGroup/Nursery should not be used for a single start call

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

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

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

           Code Smell
        44. Redundant collection functions should be avoided

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

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

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

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

           Code Smell
        49. Async functions should use async features

           Code Smell
        50. Asyncio tasks should be saved to prevent premature garbage collection

           Bug
        51. Async functions should not contain input() calls

           Bug
        52. Comprehensions only used to copy should be replaced with the respective constructor calls

           Code Smell
        53. Async functions should not contain synchronous HTTP client calls

           Bug
        54. Literal syntax should be preferred when creating empty collections or dictionaries with keyword arguments

           Code Smell
        55. Cancellation exceptions should be re-raised after cleanup

           Bug
        56. Creation of collections with literals or comprehensions should not be wrapped in type constructors

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

           Code Smell
        58. Async functions should not contain synchronous file operations

           Bug
        59. List comprehensions should not be used with "any()" or "all()"

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

           Code Smell
        61. Cancellation scopes should contain checkpoints

           Bug
        62. Async functions should not contain synchronous OS calls

           Bug
        63. Use non-blocking sleep functions in asynchronous code

           Bug
        64. Async functions should not contain synchronous subprocess calls

           Bug
        65. Long sleep durations should use sleep_forever() instead of arbitrary intervals

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

           Code Smell
        67. Asynchronous functions should not accept timeout parameters

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

           Code Smell
        69. 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
        70. PySpark's "DataFrame" column names should be unique

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

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

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

           Code Smell
        74. PySpark DataFrame toPandas function should be avoided

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

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

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

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

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

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

           Code Smell
        81. Server-side requests should not be vulnerable to traversing attacks

           Vulnerability
        82. Usage of "torch.load" can lead to untrusted code execution

           Security Hotspot
        83. Einops pattern should be valid

           Bug
        84. The "num_workers" parameter should be specified for "torch.utils.data.DataLoader"

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

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

           Code Smell
        87. Subclasses of "torch.nn.Module" should call the initializer

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

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

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

           Code Smell
        91. Transformers should not be accessed directly when a Scikit-Learn Pipeline uses caching

           Bug
        92. "memory" parameter should be specified for Scikit-Learn Pipeline

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

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

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

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

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

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

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

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

           Code Smell
        101. Numpy weekmask should have a valid value

           Code Smell
        102. datetime.datetime objects should not be compared with datetime.date objects

           Bug
        103. Dates should be formatted correctly when using "pandas.to_datetime" with "dayfirst" or "yearfirst" arguments

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

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

           Code Smell
        106. offset-naive datetime.time and datetime.datetime objects should not be compared with offset-aware ones

           Bug
        107. The 12-hour format should be used with the AM/PM marker, otherwise the 24-hour format should be used

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

           Code Smell
        109. HTTP response headers should not be vulnerable to response splitting attacks

           Vulnerability
        110. "f-strings" should not be nested too deeply

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

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

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

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

           Code Smell
        115. GraphQL introspection should be disabled in production

           Vulnerability
        116. GraphQL queries should not be vulnerable to Denial of Service attacks

           Vulnerability
        117. JWT secret keys should not be disclosed

           Vulnerability
        118. Flask secret keys should not be disclosed

           Vulnerability
        119. Stack traces should not be disclosed

           Vulnerability
        120. pandas.pipe method should be preferred over long chains of instructions

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

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

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

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

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

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

           Code Smell
        127. The abs_tol parameter should be provided when using math.isclose to compare values to 0

           Bug
        128. Equality checks should not be made against "numpy.nan"

           Bug
        129. Passing a list to np.array should be preferred over passing a generator

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

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

           Code Smell
        132. Loop boundaries should not be vulnerable to injection attacks

           Vulnerability
        133. Sequence indexes must have an __index__ method

           Bug
        134. Set members and dictionary keys should be hashable

           Bug
        135. Assignments of lambdas to variables should be replaced by function definitions

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

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

           Code Smell
        138. Memory allocations should not be vulnerable to Denial of Service attacks

           Vulnerability
        139. The "safe" flag should be set to "False" when serializing non-dictionary objects in Django JSON-encoded responses.

           Bug
        140. Fields of a Django ModelFom should be defined explicitly

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

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

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

           Code Smell
        144. Django signal handler functions should have the '@receiver' decorator on top of all other decorators

           Bug
        145. Union type expressions should be preferred over "typing.Union" in type hints

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

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

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

           Code Smell
        149. Function parameters should have type hints

           Code Smell
        150. Function returns should have type hints

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

           Code Smell
        152. ExceptionGroup and BaseExceptionGroup should not be caught with except*

           Bug
        153. Accessing sequence elements should not trigger an IndexError

           Bug
        154. Unpacking should be done with the same number of elements of the iterable.

           Bug
        155. Non-existent dictionary keys should not be accessed

           Bug
        156. Allowing unrestricted outbound communications is security-sensitive

           Security Hotspot
        157. Hard-coded secrets are security-sensitive

           Security Hotspot
        158. Collections should not be modified while they are iterated

           Bug
        159. Character classes in regular expressions should not contain only one character

           Code Smell
        160. Superfluous curly brace quantifiers should be avoided

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

           Code Smell
        162. XML signatures should be validated securely

           Vulnerability
        163. Regular expression quantifiers and character classes should be used concisely

           Code Smell
        164. Constructing arguments of system commands from user input is security-sensitive

           Security Hotspot
        165. Creating public APIs is security-sensitive

           Security Hotspot
        166. Using unencrypted EFS file systems is security-sensitive

           Security Hotspot
        167. Regular expressions should not contain empty groups

           Code Smell
        168. Using unencrypted SQS queues is security-sensitive

           Security Hotspot
        169. Allowing public network access to cloud resources is security-sensitive

           Security Hotspot
        170. Replacement strings should reference existing regular expression groups

           Bug
        171. Using unencrypted SNS topics is security-sensitive

           Security Hotspot
        172. Regular expressions should not contain multiple spaces

           Code Smell
        173. Alternation in regular expressions should not contain empty alternatives

           Bug
        174. Administration services access should be restricted to specific IP addresses

           Vulnerability
        175. Using unencrypted SageMaker notebook instances is security-sensitive

           Security Hotspot
        176. AWS IAM policies should limit the scope of permissions given

           Vulnerability
        177. Using unencrypted OpenSearch domains is security-sensitive

           Security Hotspot
        178. Policies granting access to all resources of an account are security-sensitive

           Security Hotspot
        179. Using unencrypted RDS DB resources is security-sensitive

           Security Hotspot
        180. Policies granting all privileges are security-sensitive

           Security Hotspot
        181. Applications should not create session cookies from untrusted input

           Vulnerability
        182. Allowing public ACLs or policies on a S3 bucket is security-sensitive

           Security Hotspot
        183. Using unencrypted EBS volumes is security-sensitive

           Security Hotspot
        184. Policies authorizing public access to resources are security-sensitive

           Security Hotspot
        185. Granting access to S3 buckets to all or authenticated users is security-sensitive

           Security Hotspot
        186. AWS region should not be set with a hardcoded String

           Code Smell
        187. Disabling versioning of S3 buckets is security-sensitive

           Security Hotspot
        188. Authorizing HTTP communications with S3 buckets is security-sensitive

           Security Hotspot
        189. Lambdas should not invoke other lambdas synchronously

           Code Smell
        190. Disabling server-side encryption of S3 buckets is security-sensitive

           Security Hotspot
        191. Reusable resources should be initialized at construction time of Lambda functions

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

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

           Code Smell
        194. Regex lookahead assertions should not be contradictory

           Bug
        195. Back references in regular expressions should only refer to capturing groups that are matched before the reference

           Bug
        196. Regex boundaries should not be used in a way that can never be matched

           Bug
        197. Regex patterns following a possessive quantifier should not always fail

           Bug
        198. Variables, classes and functions should be either defined or imported

           Bug
        199. Tests should be skipped explicitly

           Code Smell
        200. Assertions should not be made at the end of blocks expecting an exception

           Bug
        201. Assertions should not fail or succeed unconditionally

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

           Code Smell
        203. Assert should not be called on a tuple literal

           Bug
        204. Test methods should be discoverable

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

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

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

           Code Smell
        208. Unicode Grapheme Clusters should be avoided inside regex character classes

           Bug
        209. Type checks shouldn't be confusing

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

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

           Code Smell
        212. Regular expressions should be syntactically valid

           Bug
        213. Regex alternatives should not be redundant

           Bug
        214. Using slow regular expressions is security-sensitive

           Security Hotspot
        215. Alternatives in regular expressions should be grouped when used with anchors

           Bug
        216. Assertions comparing incompatible types should not be made

           Bug
        217. Regular expressions should not be too complicated

           Code Smell
        218. Repeated patterns in regular expressions should not match the empty string

           Bug
        219. The "open" builtin function should be called with a valid mode

           Bug
        220. Only defined names should be listed in "__all__"

           Bug
        221. Builtins should not be shadowed by local variables

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

           Code Smell
        223. Constants should not be used as conditions

           Code Smell
        224. New objects should not be created only to check their identity

           Bug
        225. Identity comparisons should not be used with cached types

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

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

           Code Smell
        228. Calls should not be made to non-callable values

           Bug
        229. "SystemExit" should be re-raised

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

           Code Smell
        231. Comparison to None should not be constant

           Code Smell
        232. Property getter, setter and deleter methods should have the expected number of parameters

           Bug
        233. Special methods should have an expected number of parameters

           Bug
        234. "self" should be the first argument to instance methods

           Code Smell
        235. Instance and class methods should have at least one positional parameter

           Bug
        236. Function parameters' default values should not be modified or assigned

           Code Smell
        237. Boolean expressions of exceptions should not be used in "except" statements

           Bug
        238. A subclass should not be in the same "except" statement as a parent class

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

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

           Code Smell
        241. Caught Exceptions must derive from BaseException

           Bug
        242. Exceptions' "__cause__" should be either an Exception or None

           Bug
        243. Special method "__exit__" should not re-raise the provided exception

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

           Code Smell
        245. Walrus operator should not make code confusing

           Code Smell
        246. JWT should be signed and verified

           Vulnerability
        247. Arguments given to functions should be of an expected type

           Code Smell
        248. Item operations should be done on objects supporting them

           Bug
        249. "in" and "not in" operators should be used on objects supporting them

           Bug
        250. Dictionary unpacking should only be done with "mapping" objects

           Bug
        251. Raised Exceptions must derive from BaseException

           Bug
        252. Operators should be used on compatible types

           Bug
        253. Unused scope-limited definitions should be removed

           Code Smell
        254. Function arguments should be passed only once

           Bug
        255. Cipher algorithms should be robust

           Vulnerability
        256. Encryption algorithms should be used with secure mode and padding scheme

           Vulnerability
        257. Server hostnames should be verified during SSL/TLS connections

           Vulnerability
        258. Server-side templates should not be vulnerable to injection attacks

           Vulnerability
        259. Insecure temporary file creation methods should not be used

           Vulnerability
        260. Using publicly writable directories is security-sensitive

           Security Hotspot
        261. HTML autoescape mechanism should not be globally disabled

           Vulnerability
        262. `str.replace` should be preferred to `re.sub`

           Code Smell
        263. Passwords should not be stored in plaintext or with a fast hashing algorithm

           Vulnerability
        264. Dynamic code execution should not be vulnerable to injection attacks

           Vulnerability
        265. Using clear-text protocols is security-sensitive

           Security Hotspot
        266. Sending emails is security-sensitive

           Security Hotspot
        267. Disabling auto-escaping in template engines is security-sensitive

           Security Hotspot
        268. NoSQL operations should not be vulnerable to injection attacks

           Vulnerability
        269. HTTP request redirections should not be open to forging attacks

           Vulnerability
        270. Logging should not be vulnerable to injection attacks

           Vulnerability
        271. Server-side requests should not be vulnerable to forging attacks

           Vulnerability
        272. Deserialization should not be vulnerable to injection attacks

           Vulnerability
        273. Endpoints should not be vulnerable to reflected cross-site scripting (XSS) attacks

           Vulnerability
        274. Having a permissive Cross-Origin Resource Sharing policy is security-sensitive

           Security Hotspot
        275. Expanding archive files without controlling resource consumption is security-sensitive

           Security Hotspot
        276. Server certificates should be verified during SSL/TLS connections

           Vulnerability
        277. Reading the Standard Input is security-sensitive

           Security Hotspot
        278. Signaling processes is security-sensitive

           Security Hotspot
        279. Using command line arguments is security-sensitive

           Security Hotspot
        280. Configuring loggers is security-sensitive

           Security Hotspot
        281. Using weak hashing algorithms is security-sensitive

           Security Hotspot
        282. Encrypting data is security-sensitive

           Security Hotspot
        283. Using regular expressions is security-sensitive

           Security Hotspot
        284. Using shell interpreter when executing OS commands is security-sensitive

           Security Hotspot
        285. Delivering code in production with debug features activated is security-sensitive

           Security Hotspot
        286. Disabling CSRF protections is security-sensitive

           Security Hotspot
        287. Unread "private" attributes should be removed

           Code Smell
        288. LDAP connections should be authenticated

           Vulnerability
        289. Cryptographic key generation should be based on strong parameters

           Vulnerability
        290. Weak SSL/TLS protocols should not be used

           Vulnerability
        291. Functions and methods should not have identical implementations

           Code Smell
        292. Collection content should not be replaced unconditionally

           Bug
        293. Unused private nested classes should be removed

           Code Smell
        294. Exceptions should not be created without being raised

           Bug
        295. Collection sizes and array length comparisons should make sense

           Bug
        296. All branches in a conditional structure should not have exactly the same implementation

           Bug
        297. Iterable unpacking, "for-in" loops and "yield from" should use an Iterable object

           Bug
        298. Variables, classes and functions should be defined before being used

           Bug
        299. Functions should use "return" consistently

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

           Code Smell
        301. Allowing both safe and unsafe HTTP methods is security-sensitive

           Security Hotspot
        302. The output of functions that don't return anything should not be used

           Bug
        303. Database queries should not be vulnerable to injection attacks

           Vulnerability
        304. Jump statements should not be redundant

           Code Smell
        305. Zero should not be a possible denominator

           Bug
        306. Functions returns should not be invariant

           Code Smell
        307. String formatting should be used correctly

           Code Smell
        308. Identity operators should not be used with dissimilar types

           Bug
        309. Conditional expressions should not be nested

           Code Smell
        310. Creating cookies without the "HttpOnly" flag is security-sensitive

           Security Hotspot
        311. Cipher Block Chaining IVs should be unpredictable

           Vulnerability
        312. "__iter__" should return an iterator

           Bug
        313. Loops without "break" should not have "else" clauses

           Code Smell
        314. Only strings should be listed in "__all__"

           Bug
        315. "pass" should not be used needlessly

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

           Code Smell
        317. Non-existent operators like "=+" should not be used

           Bug
        318. XML parsers should not be vulnerable to XXE attacks

           Vulnerability
        319. "except" clauses should do more than raise the same issue

           Code Smell
        320. "__init__" should not return a value

           Bug
        321. "__exit__" should accept type, value, and traceback arguments

           Bug
        322. "return" and "yield" should not be used in the same function

           Bug
        323. "yield" and "return" should not be used outside functions

           Bug
        324. The first argument to class methods should follow the naming convention

           Code Smell
        325. Method overrides should not change contracts

           Code Smell
        326. Regular expressions should not be vulnerable to Denial of Service attacks

           Vulnerability
        327. Setting loose POSIX file permissions is security-sensitive

           Security Hotspot
        328. Boolean expressions should not be gratuitous

           Code Smell
        329. Conditionally executed code should be reachable

           Bug
        330. Methods and properties that don't access instance data should be static

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

           Code Smell
        332. Increment and decrement operators should not be used

           Bug
        333. "<>" should not be used to test inequality

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

           Code Smell
        335. Backticks should not be used

           Code Smell
        336. String formatting should not lead to runtime errors

           Bug
        337. Python parser failure

           Code Smell
        338. Attributes should not be accessed on "None" values

           Bug
        339. Using non-standard cryptographic algorithms is security-sensitive

           Security Hotspot
        340. Using pseudorandom number generators (PRNGs) is security-sensitive

           Security Hotspot
        341. Wildcard imports should not be used

           Code Smell
        342. Return values from functions without side effects should not be ignored

           Bug
        343. Recursion should not be infinite

           Bug
        344. Unnecessary equality checks should not be made

           Bug
        345. A secure password should be used when connecting to a database

           Vulnerability
        346. Creating cookies without the "secure" flag is security-sensitive

           Security Hotspot
        347. XPath expressions should not be vulnerable to injection attacks

           Vulnerability
        348. I/O function calls should not be vulnerable to path injection attacks

           Vulnerability
        349. LDAP queries should not be vulnerable to injection attacks

           Vulnerability
        350. Formatting SQL queries is security-sensitive

           Security Hotspot
        351. OS commands should not be vulnerable to command injection attacks

           Vulnerability
        352. Hard-coded passwords are security-sensitive

           Security Hotspot
        353. Password hashing functions should use an unpredictable salt

           Vulnerability
        354. Boolean checks should not be inverted

           Code Smell
        355. Files should not be too complex

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

           Code Smell
        357. Related "if/else if" statements should not have the same condition

           Bug
        358. Unused assignments should be removed

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

           Code Smell
        360. Identical expressions should not be used on both sides of a binary operator

           Bug
        361. All code should be reachable

           Bug
        362. Loops with at most one iteration should be refactored

           Bug
        363. New-style classes should be used

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

           Code Smell
        365. Docstrings should be defined

           Code Smell
        366. "\" should only be used as an escape character outside of raw strings

           Bug
        367. "break" and "continue" should not be used outside a loop

           Bug
        368. Track "TODO" and "FIXME" comments that do not contain a reference to a person

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

           Code Smell
        370. Variables should not be self-assigned

           Bug
        371. A reason should be provided when skipping a test

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

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

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

           Code Smell
        375. Dynamically executing code is security-sensitive

           Security Hotspot
        376. Functions and lambdas should not reference variables defined in enclosing loops

           Code Smell
        377. Unused local variables should be removed

           Code Smell
        378. Track lack of copyright and license headers

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

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

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

           Code Smell
        382. Using hardcoded IP addresses is security-sensitive

           Security Hotspot
        383. Cyclomatic Complexity of classes should not be too high

           Code Smell
        384. Track uses of noqa comments

           Code Smell
        385. Track uses of "NOSONAR" comments

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

           Code Smell
        387. Floating point numbers should not be tested for equality

           Bug
        388. Track comments matching a regular expression

           Code Smell
        389. Function parameters initial values should not be ignored

           Bug
        390. Statements should be on separate lines

           Code Smell
        391. String literals should not be duplicated

           Code Smell
        392. Functions and methods should not be empty

           Code Smell
        393. Unused function parameters should be removed

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

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

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

           Code Smell
        397. Break, continue and return statements should not occur in "finally" blocks

           Bug
        398. Functions should not contain too many return statements

           Code Smell
        399. Track uses of "TODO" tags

           Code Smell
        400. Track uses of "FIXME" tags

           Code Smell
        401. Lines should not end with trailing whitespaces

           Code Smell
        402. Files should end with a newline

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

           Code Smell
        404. Unnecessary imports should be removed

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

           Code Smell
        406. Redundant pairs of parentheses should be removed

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

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

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

           Code Smell
        410. All "except" blocks should be able to catch exceptions

           Bug
        411. Files should not have too many lines of code

           Code Smell
        412. Lines should not be too long

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

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

           Code Smell

        Async functions should not contain synchronous file operations

        intentionality - efficient
        reliability
        Bug
        • async
        • asyncio
        • anyio
        • trio

        This rule raises an issue when synchronous file operations like open() are used within asynchronous functions.

        Why is this an issue?

        How can I fix it?

        More Info

        Using synchronous file operations like open() in asynchronous code blocks the entire event loop. This undermines the primary advantage of asynchronous programming - the ability to perform concurrent operations without blocking execution.

        When an async function makes a synchronous file operation:

        • The event loop is completely blocked until the file I/O operation completes
        • No other coroutines can run during this time, even if they’re ready to execute
        • The responsiveness of the application is degraded
        • In server applications, this can cause timeouts or failures for other concurrent requests

        Instead, async libraries provide mechanisms to handle file operations asynchronously:

        • aiofiles library for asyncio
        • trio.open_file() for Trio
        • anyio.open_file() for AnyIO

        Using these constructs allows other tasks to continue executing while waiting for the potentially blocking file operation to complete.

          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 ServerAnalyze code in your
          on-premise CI

        © 2026 SonarSource Sàrl. All rights reserved.

        Privacy Policy | Cookie Policy | Terms of Use