Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions tests/test_traitlets.py
Original file line number Diff line number Diff line change
Expand Up @@ -937,6 +937,32 @@ class A(HasTraits):
traits = a.traits(config_key=lambda v: True)
self.assertEqual(traits, dict(i=A.i, f=A.f, j=A.j))

def test_traits_metadata_filter_caching(self):
# metadata-filtered class_traits()/traits() results are memoized per
# class; make sure the cache preserves the "fresh dict" contract and is
# invalidated when metadata is mutated after class creation.
class A(HasTraits):
i = Int().tag(config=True)
j = Int()

# returned dict is a fresh copy the caller may mutate freely
first = A.class_traits(config=True)
self.assertEqual(first, dict(i=A.i))
first["injected"] = "oops"
self.assertEqual(A.class_traits(config=True), dict(i=A.i))

# tagging a trait after the result was cached must be reflected
A.j.tag(config=True)
self.assertEqual(A.class_traits(config=True), dict(i=A.i, j=A.j))
self.assertEqual(A().traits(config=True), dict(i=A.i, j=A.j))

# a subclass has its own cache and does not pollute the parent's
class B(A):
k = Int().tag(config=True)

self.assertEqual(B.class_traits(config=True), dict(i=A.i, j=A.j, k=B.k))
self.assertEqual(A.class_traits(config=True), dict(i=A.i, j=A.j))

def test_traits_metadata_deprecated(self):
with expected_warnings([r"metadata should be set using the \.tag\(\) method"] * 2):

Expand Down
11 changes: 8 additions & 3 deletions traitlets/config/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,14 @@
from __future__ import annotations

import functools
import json
import logging
import os
import pprint
import re
import sys
import typing as t
from collections import OrderedDict, defaultdict
from contextlib import suppress
from copy import deepcopy
from logging.config import dictConfig
from textwrap import dedent

from traitlets.config.configurable import Configurable, SingletonConfigurable
Expand Down Expand Up @@ -286,6 +283,8 @@ def _observe_logging_default(self, change: Bunch) -> None:
self._configure_logging()

def _configure_logging(self) -> None:
from logging.config import dictConfig

config = self.get_default_logging_config()
nested_update(config, self.logging_config or {})
dictConfig(config)
Expand Down Expand Up @@ -483,6 +482,8 @@ def start_show_config(self) -> None:
cls_config.pop("show_config_json", None)

if self.show_config_json:
import json

json.dump(config, sys.stdout, indent=1, sort_keys=True, default=repr)
# add trailing newline
sys.stdout.write("\n")
Expand All @@ -498,6 +499,8 @@ def start_show_config(self) -> None:
class_config = config[classname]
if not class_config:
continue
import pprint

print(classname)
pformat_kwargs: StrDict = dict(indent=4, compact=True) # noqa: C408

Expand Down Expand Up @@ -929,6 +932,8 @@ def _load_config_files(
if log:
log.debug("Loaded config file: %s", loader.full_filename)
if config:
import json

for filename, earlier_config in zip(filenames, loaded, strict=True):
collisions = earlier_config.collisions(config)
if collisions and log:
Expand Down
11 changes: 7 additions & 4 deletions traitlets/config/configurable.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,12 +171,15 @@ def _load_config(
) -> None:
"""load traits from a Config object"""

my_config = self._find_my_config(cfg)
if not my_config:
# Nothing in the config applies to this instance; avoid the cost of
# computing traits() and entering hold_trait_notifications() for the
# many leaf Configurables that carry no matching config.
return

if traits is None:
traits = self.traits(config=True)
if section_names is None:
section_names = self.section_names()

my_config = self._find_my_config(cfg)

# hold trait notifications until after all config has been loaded
with self.hold_trait_notifications():
Expand Down
5 changes: 4 additions & 1 deletion traitlets/config/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import argparse
import copy
import functools
import json
import os
import re
import sys
Expand Down Expand Up @@ -565,6 +564,8 @@ def load_config(self) -> Config:
return self.config

def _read_file_as_dict(self) -> dict[str, t.Any]:
import json

with open(self.full_filename) as f:
return t.cast("dict[str, t.Any]", json.load(f))

Expand All @@ -591,6 +592,8 @@ def __exit__(self, exc_type: object, exc_value: object, traceback: object) -> No
configuration to disk.
"""
self.config.version = 1
import json

json_config = json.dumps(self.config, indent=2)
with open(self.full_filename, "w") as f:
f.write(json_config)
Expand Down
Loading