N
N
nishe2022-03-21 13:50:57
Python
nishe, 2022-03-21 13:50:57

How efficient is my code if I read it in its entirety each time to change the key-value of the store?

I created a console script to work with key-value storage. In order to read some value from it by key or add a new value, I read it completely every time. Is this normal practice or should I do something else?
The storage works like this: passing --key --value creates a value for the key (or adds it if the key already exists). Passing --key prints the key values.

import os
import tempfile
import argparse
import json

import os
import tempfile

parser = argparse.ArgumentParser()
parser.add_argument('--key')
parser.add_argument('--value')
parser_args = parser.parse_args()
storage_path = os.path.join(tempfile.gettempdir(), 'storage.data')

try:
    with open(storage_path, 'r') as f:
        data = json.load(f)
except json.decoder.JSONDecodeError:
    data = {}
    with open(storage_path, 'w') as f:
        json.dump(data, f)
except FileNotFoundError:
    data = {}
    with open(storage_path, 'w') as f:
        json.dump(data, f)

if parser_args.value is None:
    with open(storage_path, 'r') as f:
        data = json.load(f)
        try:
            print(*data[parser_args.key], sep=', ')
        except KeyError:
            print(None)

if (parser_args.key is not None) and (parser_args.value is not None):
    with open(storage_path, 'r') as f:
        data_local = json.load(f)
    with open(storage_path, 'w') as f:
        try:
            data_local[parser_args.key].append(parser_args.value)
        except KeyError:
            data_local[parser_args.key] = [parser_args.value]
        json.dump(data_local, f, indent=4)

PS what is the best way to write: if smth is None or is it better to write if smth?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2022-03-21
@nishe

In order to read some value from it by key or add a new value, I read it completely every time. Is this normal practice or should I do something else?

See what "norm" is. If it's just something to play with, it's fine. If there are a couple of hundred keys or less in the vault, it's fine. If there are no loads, it's fine. For real projects - not normal. The complexity of each operation is O(n), apart from the fact that opening files is also an expensive operation. SQLite with one table and an index on key as key-value storage will be many times faster.
PS what is the best way to write: if smth is None or is it better to write if smth?

These are two different checks. smth is None will return False if smth is 0 or an empty list or other falsy object. I prefer to write is None always when the type is Optional[T] to avoid the case when a non-None but falsy value came, otherwise you can hide the error

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question