Coverage for chebpy/core/settings.py: 100%
33 statements
« prev ^ index » next coverage.py v7.10.2, created at 2025-08-07 10:30 +0000
« prev ^ index » next coverage.py v7.10.2, created at 2025-08-07 10:30 +0000
1"""Configuration and preferences management for the ChebPy package.
3This module provides classes for managing preferences and settings in ChebPy.
4It implements a singleton pattern for the preferences object, ensuring that
5all parts of the package use the same settings. It also provides a context
6manager interface for temporarily changing preferences.
8The main classes are:
9- DefaultPreferences: Defines the default values for all preferences
10- ChebPreferences: The actual preferences object used throughout the package
12The module creates a singleton instance of ChebPreferences called _preferences,
13which is imported by other modules to access the current settings.
14"""
16import numpy as np
19class DefaultPreferences:
20 """Default preferences for chebpy."""
22 eps = np.finfo(float).eps
23 tech = "Chebtech"
24 domain = np.array([-1.0, 1.0]) # TODO: should this be .utilities.Domain?
25 N_plot = 2001
26 maxpow2 = 16
27 maxiter = 10
28 sortroots = False
29 mergeroots = True
31 @classmethod
32 def _defaults(cls):
33 """Returns all defined class attributes."""
34 return {k: v for k, v in cls.__dict__.items() if k[0] != "_"}
37class ChebPreferences(DefaultPreferences):
38 """Preferences object used in chebpy."""
40 def reset(self, *names):
41 """Reset default preferences.
43 `.reset()` resets all preferences to the DefaultPrefs state
44 `.reset(*names)` resets only the selected ones.
45 This leaves additional user-added prefs untouched.
46 """
47 if len(names) == 0:
48 names = DefaultPreferences._defaults()
49 for name in names:
50 if hasattr(DefaultPreferences, name):
51 setattr(self, name, getattr(DefaultPreferences, name))
53 # Singleton
54 _instance = None # persistent reference for the singleton object
56 def __new__(cls):
57 """Create or return the singleton instance of ChebPreferences.
59 This method implements the singleton pattern, ensuring that only one
60 instance of ChebPreferences exists. If an instance already exists,
61 it returns that instance; otherwise, it creates a new one.
63 Args:
64 cls (type): The class being instantiated (ChebPreferences).
66 Returns:
67 ChebPreferences: The singleton instance of ChebPreferences.
68 """
69 if cls._instance is None:
70 cls._instance = super(DefaultPreferences, cls).__new__(cls)
71 return cls._instance
73 # Context manager
74 _stash = [] # persistent stash for old prefs when entering context(s)
76 def __enter__(self):
77 """Save current preferences when entering a context.
79 This method is called when entering a context manager block. It saves
80 the current preferences to a stack so they can be restored when exiting
81 the context.
83 Args:
84 self (ChebPreferences): The preferences object.
86 Returns:
87 ChebPreferences: The preferences object (self._instance).
88 """
89 self._stash.append({k: getattr(self, k) for k in DefaultPreferences._defaults().keys()})
90 return self._instance
92 def __exit__(self, exc_type, exc_value, traceback):
93 """Restore previous preferences when exiting a context.
95 This method is called when exiting a context manager block. It restores
96 the preferences to their previous values by popping the stashed values
97 from the stack and setting them back on the object.
99 Args:
100 self (ChebPreferences): The preferences object.
101 exc_type: The exception type, if an exception was raised in the context.
102 exc_value: The exception value, if an exception was raised in the context.
103 traceback: The traceback, if an exception was raised in the context.
104 """
105 for k, v in self._stash.pop().items():
106 setattr(self, k, v)
109# create the singleton object for easy import in sister modules
110_preferences = ChebPreferences()