A versatile Python utility for managing application context through in-memory and persistent object storage.
ContextManager provides a streamlined way to save, load, and manage objects across your application's lifecycle. It offers both in-memory caching and file-based persistence, supporting multiple serialization formats, making it ideal for:
- Application state management
- Configuration persistence
- Object caching
- Data sharing between components
- Session management
- Dual Storage System: Store objects both in memory and on disk
- Multiple Serialization Formats: Support for both Pickle (binary) and JSON (text-based) serialization
- Context Management: Use as a context manager with Python's
with
statement - Simple API: Intuitive methods for saving, loading, and deleting objects
- Context Listing: Ability to list all available contexts
- Bulk Operations: Clear all objects with a single call
# Clone the repository
git clone https://github.com/yourusername/context-manager.git
# Navigate to the project directory
cd context-manager
# Install the package
pip install -e .
from context import ContextManager
# Create a context manager instance
context = ContextManager()
# Save objects with different formats
user_data = {"name": "Alice", "age": 30}
context.save(user_data, "user_profile", file_format="json")
complex_data = {"model": SomeModel(), "history": [1, 2, 3]}
context.save(complex_data, "app_state", file_format="pickle")
# Load objects
user = ContextManager.load("user_profile", file_format="json")
state = ContextManager.load("app_state", file_format="pickle")
# List all available contexts
contexts = ContextManager.list_contexts()
print(f"Available contexts: {contexts}")
# Delete a specific context
context.delete("user_profile")
# Clear all contexts
ContextManager.clear()
with ContextManager() as context:
# Operations within a context
context.save({"settings": "value"}, "app_settings", file_format="json")
settings = ContextManager.load("app_settings", file_format="json")
Creates a new instance of the ContextManager class.
Saves an object to the specified context.
- obj: The Python object to save
- context_name: A string identifier for the context
- file_format: Either "pickle" or "json" (default: "pickle")
Loads an object from the specified context.
- context_name: The string identifier for the context
- file_format: Either "pickle" or "json" (default: "pickle")
- Returns: The loaded object
Removes an object from memory and deletes associated files.
- context_name: The string identifier for the context to delete
Returns a list of all available context names currently in memory.
Removes all objects from memory and deletes all saved files.
Objects are stored in:
- Memory: Using an internal class dictionary
_objects
- Disk: In the
object_saver_files
directory relative to the script location
- Supports all Python objects (including custom classes)
- Binary format (not human-readable)
- Not portable across Python versions or implementations
- Use for complex objects that can't be serialized to JSON
- Human-readable text format
- Limited to JSON-serializable types (dicts, lists, strings, numbers, booleans, None)
- Portable across languages and systems
- Use for configuration, settings, and data that needs to be readable
-
Security Considerations:
- Pickle files can execute arbitrary code when loaded. Only load pickle files from trusted sources.
- Consider implementing encryption for sensitive data.
-
Performance Optimization:
- For frequently accessed objects, use in-memory access after the first load.
- For large objects, consider implementing lazy loading or compression.
-
Error Handling:
- Implement try/except blocks when loading potentially corrupted files.
- Consider adding validation for loaded objects.
-
File Management:
- For production use, consider customizing the file storage location.
- Implement periodic cleanup of unused context files.
The ContextManager uses a class variable _objects
to store all objects in memory across instances, allowing class methods to access the same objects as instance methods. File operations are implemented using Python's standard libraries:
pickle
for binary serializationjson
for text-based serializationos
for file operations
Potential extensions include:
- Adding support for additional serialization formats (YAML, TOML, etc.)
- Implementing data compression
- Adding encryption for sensitive data
- Supporting network storage backends
- Adding TTL (time-to-live) for cached objects
- Implementing concurrency controls for multi-threaded access
Contributions are welcome! Please feel free to submit a Pull Request.