MCPcopy Create free account
hub / github.com/ipython/traitlets / JSONFileConfigLoader

Class JSONFileConfigLoader

traitlets/config/loader.py:553–605  ·  view source on GitHub ↗

A JSON file loader for config Can also act as a context manager that rewrite the configuration file to disk on exit. Example:: with JSONFileConfigLoader('myapp.json','/home/jupyter/configurations/') as c: c.MyNewConfigurable.new_value = 'Updated'

Source from the content-addressed store, hash-verified

551
552
553class JSONFileConfigLoader(FileConfigLoader):
554 """A JSON file loader for config
555
556 Can also act as a context manager that rewrite the configuration file to disk on exit.
557
558 Example::
559
560 with JSONFileConfigLoader('myapp.json','/home/jupyter/configurations/') as c:
561 c.MyNewConfigurable.new_value = 'Updated'
562
563 """
564
565 def load_config(self) -> Config:
566 """Load the config from a file and return it as a Config object."""
567 self.clear()
568 try:
569 self._find_file()
570 except OSError as e:
571 raise ConfigFileNotFound(str(e)) from e
572 dct = self._read_file_as_dict()
573 self.config = self._convert_to_config(dct)
574 return self.config
575
576 def _read_file_as_dict(self) -> dict[str, t.Any]:
577 with open(self.full_filename) as f:
578 return t.cast("dict[str, t.Any]", json.load(f))
579
580 def _convert_to_config(self, dictionary: dict[str, t.Any]) -> Config:
581 if "version" in dictionary:
582 version = dictionary.pop("version")
583 else:
584 version = 1
585
586 if version == 1:
587 return Config(dictionary)
588 else:
589 raise ValueError(f"Unknown version of JSON config file: {version}")
590
591 def __enter__(self) -> Config:
592 self.load_config()
593 return self.config
594
595 def __exit__(self, exc_type: object, exc_value: object, traceback: object) -> None:
596 """
597 Exit the context manager but do not handle any errors.
598
599 In case of any error, we do not want to write the potentially broken
600 configuration to disk.
601 """
602 self.config.version = 1
603 json_config = json.dumps(self.config, indent=2)
604 with open(self.full_filename, "w") as f:
605 f.write(json_config)
606
607
608class PyFileConfigLoader(FileConfigLoader):

Callers 4

test_jsonMethod · 0.90
test_context_managerMethod · 0.90
test_v2raiseMethod · 0.90

Calls

no outgoing calls

Tested by 4

test_jsonMethod · 0.72
test_context_managerMethod · 0.72
test_v2raiseMethod · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…