All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.py.rules.python.S5828.html Maven / Gradle / Ivy

There is a newer version: 4.23.0.17664
Show newest version

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.

with open("test.txt", "aw") as f:  # Noncompliant: ValueError
    pass

Compliant solution

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





© 2015 - 2024 Weber Informatics LLC | Privacy Policy