2023-06-30 09:16:01 +02:00

81 lines
2.2 KiB
Plaintext

This rule raises an issue when an invalid "mode" is provided to the `open` builtin function.
== Why is this an issue?
The `open` builtin function can open files in different modes. These modes are provided as a combination of characters. Using an invalid sequence of characters will make `open` fail with a `ValueError`.
A valid mode:
* should contain only one of the following characters: `r` (read), `w` (write), `a` (append), `x` (create).
* should contain zero or one of the following characters: `t` (text), `b` (binary).
* should contain zero or one `+` character (open for updating)
For example: `a`, `rt`, `r+` and `w+b` are valid modes.
If no `t` or `b` character is provided the mode will default to `t` (text), so specifying `r` is equivalent to `rt`.
*Note*: __In Python 2, providing an incorrect mode may have an undefined behavior (ex: it might ignore some characters)__
== How to fix it
Make sure to provide a valid mode to the `open` builtin function.
=== Code examples
==== Noncompliant code example
In Python 3 the following program will throw a `ValueError`.
In Python 2.7.16 on MacOs, `open` will just ignore the `w` flag.
[source,python,diff-id=1,diff-type=noncompliant]
----
with open("test.txt", "aw") as f: # Noncompliant: ValueError
pass
----
==== Compliant solution
[source,python,diff-id=1,diff-type=compliant]
----
with open("test.txt", "a") as f:
pass
----
=== Pitfalls
In Python 2, the character `U` (universal newlines) is available as a mode character but it cannot be combined with `a`, `w`, `x` or `+`.
*Note*: __``++U++`` has no effect in Python 3, it is deprecated and is replaced by the parameter `newline` of the `open` function. The default value of `newline` is `None`, meaning universal newlines mode is enabled.__
== Resources
=== Documentation
* https://docs.python.org/3/library/functions.html#open[The `open` builtin function]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Fix this invalid mode string.
=== Highlighting
The mode parameter
'''
== Comments And Links
(visible only on this page)
=== is related to: S5488
endif::env-github,rspecator-view[]