Unbrok3n
Unbrok3n

Reputation: 27

What is the correct way to save variable data in python

I have some useful scripts written in python that helps me with testing of the project (some complicated price calculation system). Before starting price calculation of any product i need to parse server for values that are related only to required product. This parsing requires time, about 5 sec. Given, that I know when i need to update values from server, I don't need to wait these 5 seconds each time when i launch my method that calculates price for me. In this case i need to store parsed info inside variable and use it for further price calculation. But sometimes i also need to update my info with server. simplified code example:

class Some_scripts(object):
    def __init__(self):
        pass

    def parser(self, endpoint, additional_requirements):
        some_parsing_code
        return required_info  # example of returned data [{"name":"John"}, {"name":"Jack"}...]

    def car_price_calc(self):
        self.required_values = self.parser(endpoint, additional_requirements)  # this one i need to store
        futher_work_with
        self.required_value

The first thing that comes to my mind, simply write self.required_valuesinto file and add some additional flag that indicates method about updating self.required_values from server or just taking it from file. But is it the most correct, reliable way of solving my question?

Upvotes: 0

Views: 1532

Answers (1)

Peter Smit
Peter Smit

Reputation: 1644

Depends on you use case. Pickling is the nicest way of writing python variables to file, if you intent to read it with python again. https://docs.python.org/3/library/pickle.html

Other solutions would be plain text files, or somewhat structured text format, like JSON or YAML. Those are more useful for human reading, or using your values in a different language.

Upvotes: 5

Related Questions