Skip to main content

Ein thread-sicherer In-Memory Speicher, basierend auf Python-Dictionaries.

Project description

python_storageObject

The StorageObject class is a thread-safe, in-memory storage solution that manages key-value pairs using Python’s built-in dictionary. It incorporates a reentrant lock (RLock) to prevent race conditions during concurrent access, ensuring data consistency even when multiple threads read or modify the data simultaneously. Designed for scenarios like caching, shared state management, and session handling, StorageObject provides a clear and concise API that maintains thread safety while efficiently managing concurrent data operations.


Table of Contents


Installation

You can integrate StorageObject into your project by following these steps:

  1. Clone or Download the Repository:

    git clone https://github.com/Mogduz/python_storageObject.git
    cd python_storageObject
    
  2. Install in Development Mode:

    Use pip to install the package in editable mode so that changes to the source code are immediately available:

    pip install -e .
    

    Alternatively, if the package is published on PyPI, you can install it directly:

    pip install storageObject
    

Usage

  1. Basic Operations:

    Import the StorageObject class and create an instance to perform basic operations:

    from storageobject import StorageObject
    
    # Create an instance of StorageObject
    storage = StorageObject()
    
    # Set a value for a key
    storage.set('user', 'Alice')
    
    # Retrieve the value for a key
    value = storage.get('user')
    print(value)  # Output: Alice
    
    # Check if a key exists
    if storage.has('user'):
        print("Key 'user' exists.")
    
    # Remove a key-value pair
    storage.remove('user')
    
  2. Batch Operations: You can perform operations on multiple keys at once using the batch methods:

    # Set multiple key-value pairs
    data = {'a': 1, 'b': 2, 'c': 3}
    store.set_many(data)
    
    # Retrieve multiple values as a list
    values_list = store.get_many(['a', 'b', 'c'])
    print(values_list)  # Output: [1, 2, 3]
    
    # Retrieve multiple values as a dictionary
    values_dict = store.get_many(['a', 'b', 'c'], withKeys=True)
    print(values_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}
    
    # Remove multiple key-value pairs
    store.remove_many(['a', 'b'])
    

API Reference

Constructor

  • StorageObject()

    Creates a new instance with an internally managed dictionary and a reentrant lock.

Methods

  • set(key: str, value: any) -> None

    Assigns the given value to the specified key.

  • has(key: str) -> bool

    Checks whether the specified key exists in the storage.

  • get(key: str, default: any = None) -> any

    Retrieves the value for the given key, returning the default value if the key is not found.

  • remove(key: str) -> None

    Removes the key-value pair if the key exists.

  • set_many(mapping: dict[str, any]) -> None

    Sets multiple key-value pairs at once using the provided dictionary.

  • get_many(keys: list[str], defaults: any = None, withKeys: bool = False) -> list | dict

    Retrieves values for a list of keys. Returns a list if withKeys is False, otherwise returns a dictionary mapping keys to their values.

  • remove_many(keys: list[str]) -> None

    Removes multiple key-value pairs based on the provided list of keys.

Properties

  • _lock

    Provides access to the internal reentrant lock for thread safety.

  • _data

    Provides access to the internal dictionary holding all key-value pairs.

Examples

Here's a complete example demonstrating the usage of StorageObject:

from storageobject import StorageObject

def main():
    # Create a storage instance
    store = StorageObject()

    # Set individual key-value pairs
    store.set('name', 'Bob')
    store.set('age', 30)

    # Set multiple values at once
    store.set_many({'city': 'New York', 'country': 'USA'})

    # Retrieve and print individual values
    print("Name:", store.get('name'))
    print("Age:", store.get('age'))

    # Retrieve multiple values as a dictionary
    data = store.get_many(['name', 'city'], withKeys=True)
    print("Data (as dict):", data)

    # Remove a key-value pair and verify removal
    store.remove('age')
    print("Age after removal:", store.get('age', 'Not Found'))

if __name__ == "__main__":
    main()        

Running Tests

Unit tests are provided to ensure StorageObject functions correctly. To run the tests, navigate to the project's root directory and execute:

python -m unittest discover -s tests

Make sure you execute this command from the root directory so that the package is properly located in the PYTHONPATH.

Contributing

Contributions are welcome! To contribute:

  1. Fork the repository.

  2. Create a new branch for your changes (e.g., git checkout -b feature/new-feature).

  3. Commit and push your changes.

  4. Open a pull request with a detailed description of your modifications.

For any questions or support, please open an issue in the repository.

License

This project is licensed under the MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

storageobject-1.0.0.tar.gz (8.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

storageobject-1.0.0-py3-none-any.whl (7.7 kB view details)

Uploaded Python 3

File details

Details for the file storageobject-1.0.0.tar.gz.

File metadata

  • Download URL: storageobject-1.0.0.tar.gz
  • Upload date:
  • Size: 8.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for storageobject-1.0.0.tar.gz
Algorithm Hash digest
SHA256 0fd8b8939248b2f55b9700c6ebc481a4463e73f90fe920c18ee39d0152007ba1
MD5 98fec27a9e6201dd5ecd5a13421f5bea
BLAKE2b-256 3df1d0da76b4a6590889dbc3edddc2213b7b8d98993ba09e8087e4b35ee3ea7e

See more details on using hashes here.

File details

Details for the file storageobject-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: storageobject-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 7.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for storageobject-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 41cf9084d204e3f84fff4037115ec23fe233a9643f9187d71d4f1b7549c25329
MD5 260a25bcf0554523e49d10f9f53ebd00
BLAKE2b-256 eea69b295ca2b575fee43a5c50f19f4a5add499084f3292a973d20102a914b37

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page