Python

Python

Made by DeepSource

Unnecessary use of json.dumps() for file data PY-W0079

Anti-pattern
Major
Autofix

The json module provides two ways to write JSON data: a .dumps() method that accepts a JSON string, and a .dump() method, that works with files directly. So instead of using json.dumps() and writing to a file manually, it is recommended to use json.dump() directly.

Bad practice

with open('data.json', 'w') as file:
    file.write(json.dumps(data))  # Writing to file manually

class Socket:
    def write_data(self, data):
        self.socket.write(json.dumps(data))  # Writing to socket manually
        self.socket.close()

Recommended

with open('data.json', 'w') as file:
    json.dump(data, file)  # Directly passing the file object

class Socket:
    def write_data(self, data):
        json.dump(data, self.socket)  # Directly passing the socket object
        self.socket.close()