Answer the question
In order to leave comments, you need to log in
Parse json file and make it available after initialization?
Hello, I have been learning python for a couple of days. The question is:
I have a json config file. There is a base class that also collects information from configs. How can I, after initialization, store information somewhere without parsing this file again. I would like to import this class and just refer to it as an array. How to do it?
Answer the question
In order to leave comments, you need to log in
The pattern is called a singleton.
class EnvironmentSetup(unittest.TestCase):
base_config = None
@classmethod
def setUpClass(cls):
cls.base_config = cls.setConfig()
@classmethod
def setConfig(cls):
with open('../config.json') as file:
config = json.load(file)
return config
def __new__(cls):
# Перекрываем создание объекта класса
if not hasattr(cls, 'instance'):
cls.instance = super().__new__(cls)
return cls.instance
You probably parse it with regular expressions, while all normal people use the json library.
the function just parses it into a variable of type dict or list (it depends on the content) and then you access it as a dictionary array.config=json.load(open("config.json"))
>>>config["myint"]
1
>>>config["mystring"]
'string'
>>>config["myarray"][0]
'item1'
Class 1 (initializing)
class EnvironmentSetup(unittest.TestCase):
base_config = None
@classmethod
def setUpClass(cls):
cls.base_config = cls.setConfig()
@classmethod
def setConfig(cls):
with open('../config.json') as file:
config = json.load(file)
return config
from tests.base.test import EnvironmentSetup as base_test
class Another:
def __init__(self, params):
print(base_test.base_config) -> Получаю None соответственно
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question