classmods


Nameclassmods JSON
Version 1.0.0 PyPI version JSON
download
home_pagehttps://github.com/hmohammad2520-org/classmods/
SummarySimple mods for python classes.
upload_time2025-07-28 08:16:34
maintainerNone
docs_urlNone
authorhmohammad2520-org
requires_python>=3.9
licenseMIT License Copyright (c) 2025 Radin-System Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "classmods"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords python class mods modification descriptors methods methodmod methodobserve
VCS
bugtrack_url
requirements python-dotenv pytest setuptools
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # classmods

`classmods` is a lightweight Python package designed to enhance class behavior with minimal effort. It provides modular decorators and descriptors to automate and simplify class-related tasks like environment variable management, creating example env files, monitoring, logging, and more.

# Documentation

All features are well documented and use a high level of `type_hints` for easy understanding and usage.

## Features

* `ConstantAttrib`: A descriptor that acts like a constant. Once set, the value cannot be changed. Raises `AttributeError` on change detection.
* `RemoteAttrib`: A descriptor that acts as a remote attribute. You can modify the mapped value on-the-fly.
* `ENVMod`: The main API class for managing `.env` variables. Supports manual and decorator-based registration of environment items, type-safe value loading, and `.env_example` generation.
* `MethodMonitor`: A class to monitor method calls of a target class, triggering a handler function after the method is called.
* `logwrap`: A dynamic decorator to log function calls. Uses the `logging` module with your current project configurations.
* `suppress_errors`: A decorator that suppresses exceptions raised by the wrapped function and returns a fallback value instead.

## Installation

1. Easy install with pip

```bash
pip install classmods
```

2. Install with git+pip

```bash
pip install git+https://github.com/hmohammad2520-org/classmods
```

## Examples

### Constant Attribute

```python
from classmods import ConstantAttrib

class Config:
    app_name = ConstantAttrib[str]()

    def __init__(self, app_name):
        self.app_name = app_name

config = Config('new app')
config.app_name = 'my app'  # This will raise AttributeError
```

### Remote Attribute

```python
import requests
from classmods import RemoteAttrib

class Config:
    token = RemoteAttrib[str](
        get=lambda: requests.get("https://api.example.com/auth").json()["token"],
        cache_timeout=10,  # keeps result for 10 seconds
    )

config = Config()
token = config.token  # This will send a request and return the result
```

### ENVMod

```python
from os import PathLike
from requests import Session
from classmods import ENVMod

class Config:
    ENVMod.register(exclude=['session'], cast={'log_path': str})
    def __init__(
        self,
        app_name: str,
        session: Session,  # Excluded non-parsable object
        log_path: PathLike,
        log_level: Optional[str] = None,
        port: int = 10,
    ):
        '''
        Args:
            app_name (str): Application name.
            session (Session): Requests session.
            log_path (PathLike): Path of log file.
            log_level (Optional[str]): Log level, e.g., info.
            port (int): Session port, defaults to 10.
        '''

ENVMod.save_example('.my_example_path')
ENVMod.load_dotenv('.my_env')
ENVMod.sync_env_file('.my_env')
config = Config(**ENVMod.load_args(Config.__init__), session=Session())
```

### Method Monitor

```python
from classmods import MethodMonitor

class MyClass:
    def my_method(self):
        pass

def my_handler(instance):
    print(f"Monitor triggered on {instance}")

monitor = MethodMonitor(MyClass, my_handler, target_method='my_method')
obj = MyClass()
obj.my_method()
```

### logwrap

```python
from classmods import logwrap

@logwrap(before=('INFO', '{func} starting, args={args} kwargs={kwargs}'), after=('INFO', '{func} ended'))
def my_func(my_arg, my_kwarg=None):
    ...

my_func('hello', my_kwarg=123)  # Check logs to see the output
```

### Suppress Errors

```python
from classmods import suppress_errors

@suppress_errors(Exception)
def risky_op() -> int:
    return 1 / 0

result = risky_op()  # result = ZeroDivisionError

@suppress_errors(False)
def safe_op() -> bool:
    raise ValueError("error")

result = safe_op()  # result = False
```

## License

MIT License

---

Made with ❤️ by [hmohammad2520](https://github.com/hmohammad2520-org)

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/hmohammad2520-org/classmods/",
    "name": "classmods",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "python, class, mods, modification, descriptors, methods, methodmod, methodobserve",
    "author": "hmohammad2520-org",
    "author_email": "hmohammad2520-org <hmohammad2520@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/2b/d1/0a0c0b3c211e849a3b7c9eb32c49806f1ef4cefc6f4558e21b9c1e3d0e14/classmods-1.0.0.tar.gz",
    "platform": null,
    "description": "# classmods\n\n`classmods` is a lightweight Python package designed to enhance class behavior with minimal effort. It provides modular decorators and descriptors to automate and simplify class-related tasks like environment variable management, creating example env files, monitoring, logging, and more.\n\n# Documentation\n\nAll features are well documented and use a high level of `type_hints` for easy understanding and usage.\n\n## Features\n\n* `ConstantAttrib`: A descriptor that acts like a constant. Once set, the value cannot be changed. Raises `AttributeError` on change detection.\n* `RemoteAttrib`: A descriptor that acts as a remote attribute. You can modify the mapped value on-the-fly.\n* `ENVMod`: The main API class for managing `.env` variables. Supports manual and decorator-based registration of environment items, type-safe value loading, and `.env_example` generation.\n* `MethodMonitor`: A class to monitor method calls of a target class, triggering a handler function after the method is called.\n* `logwrap`: A dynamic decorator to log function calls. Uses the `logging` module with your current project configurations.\n* `suppress_errors`: A decorator that suppresses exceptions raised by the wrapped function and returns a fallback value instead.\n\n## Installation\n\n1. Easy install with pip\n\n```bash\npip install classmods\n```\n\n2. Install with git+pip\n\n```bash\npip install git+https://github.com/hmohammad2520-org/classmods\n```\n\n## Examples\n\n### Constant Attribute\n\n```python\nfrom classmods import ConstantAttrib\n\nclass Config:\n    app_name = ConstantAttrib[str]()\n\n    def __init__(self, app_name):\n        self.app_name = app_name\n\nconfig = Config('new app')\nconfig.app_name = 'my app'  # This will raise AttributeError\n```\n\n### Remote Attribute\n\n```python\nimport requests\nfrom classmods import RemoteAttrib\n\nclass Config:\n    token = RemoteAttrib[str](\n        get=lambda: requests.get(\"https://api.example.com/auth\").json()[\"token\"],\n        cache_timeout=10,  # keeps result for 10 seconds\n    )\n\nconfig = Config()\ntoken = config.token  # This will send a request and return the result\n```\n\n### ENVMod\n\n```python\nfrom os import PathLike\nfrom requests import Session\nfrom classmods import ENVMod\n\nclass Config:\n    ENVMod.register(exclude=['session'], cast={'log_path': str})\n    def __init__(\n        self,\n        app_name: str,\n        session: Session,  # Excluded non-parsable object\n        log_path: PathLike,\n        log_level: Optional[str] = None,\n        port: int = 10,\n    ):\n        '''\n        Args:\n            app_name (str): Application name.\n            session (Session): Requests session.\n            log_path (PathLike): Path of log file.\n            log_level (Optional[str]): Log level, e.g., info.\n            port (int): Session port, defaults to 10.\n        '''\n\nENVMod.save_example('.my_example_path')\nENVMod.load_dotenv('.my_env')\nENVMod.sync_env_file('.my_env')\nconfig = Config(**ENVMod.load_args(Config.__init__), session=Session())\n```\n\n### Method Monitor\n\n```python\nfrom classmods import MethodMonitor\n\nclass MyClass:\n    def my_method(self):\n        pass\n\ndef my_handler(instance):\n    print(f\"Monitor triggered on {instance}\")\n\nmonitor = MethodMonitor(MyClass, my_handler, target_method='my_method')\nobj = MyClass()\nobj.my_method()\n```\n\n### logwrap\n\n```python\nfrom classmods import logwrap\n\n@logwrap(before=('INFO', '{func} starting, args={args} kwargs={kwargs}'), after=('INFO', '{func} ended'))\ndef my_func(my_arg, my_kwarg=None):\n    ...\n\nmy_func('hello', my_kwarg=123)  # Check logs to see the output\n```\n\n### Suppress Errors\n\n```python\nfrom classmods import suppress_errors\n\n@suppress_errors(Exception)\ndef risky_op() -> int:\n    return 1 / 0\n\nresult = risky_op()  # result = ZeroDivisionError\n\n@suppress_errors(False)\ndef safe_op() -> bool:\n    raise ValueError(\"error\")\n\nresult = safe_op()  # result = False\n```\n\n## License\n\nMIT License\n\n---\n\nMade with \u2764\ufe0f by [hmohammad2520](https://github.com/hmohammad2520-org)\n",
    "bugtrack_url": null,
    "license": "MIT License\n        \n        Copyright (c) 2025 Radin-System\n        \n        Permission is hereby granted, free of charge, to any person obtaining a copy\n        of this software and associated documentation files (the \"classmods\"), to deal\n        in the Software without restriction, including without limitation the rights\n        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n        copies of the Software, and to permit persons to whom the Software is\n        furnished to do so, subject to the following conditions:\n        \n        The above copyright notice and this permission notice shall be included in all\n        copies or substantial portions of the Software.\n        \n        THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n        SOFTWARE.\n        ",
    "summary": "Simple mods for python classes.",
    "version": "1.0.0",
    "project_urls": {
        "BugTracker": "https://github.com/hmohammad2520-org/classmods/issues",
        "Homepage": "https://github.com/hmohammad2520-org/classmods"
    },
    "split_keywords": [
        "python",
        " class",
        " mods",
        " modification",
        " descriptors",
        " methods",
        " methodmod",
        " methodobserve"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "bf3aea7b19ca6086a4876659b40ca426645378d4d39fca7ce2b07c6c6ccc1c21",
                "md5": "6b408538b30c893ce47afd27188606a2",
                "sha256": "0bb8b5eb699552ab7c1d49b7bf77d4994545c71e87aa96047fad747423f554ad"
            },
            "downloads": -1,
            "filename": "classmods-1.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "6b408538b30c893ce47afd27188606a2",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 14622,
            "upload_time": "2025-07-28T08:16:32",
            "upload_time_iso_8601": "2025-07-28T08:16:32.956568Z",
            "url": "https://files.pythonhosted.org/packages/bf/3a/ea7b19ca6086a4876659b40ca426645378d4d39fca7ce2b07c6c6ccc1c21/classmods-1.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "2bd10a0c0b3c211e849a3b7c9eb32c49806f1ef4cefc6f4558e21b9c1e3d0e14",
                "md5": "71b284254a5c2fb1c70e3d24e47696fc",
                "sha256": "6680a1d4f39c7d38d661a3ee40f5ad64ed8ef4088cd8099043d00bcb273984ab"
            },
            "downloads": -1,
            "filename": "classmods-1.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "71b284254a5c2fb1c70e3d24e47696fc",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 14565,
            "upload_time": "2025-07-28T08:16:34",
            "upload_time_iso_8601": "2025-07-28T08:16:34.284778Z",
            "url": "https://files.pythonhosted.org/packages/2b/d1/0a0c0b3c211e849a3b7c9eb32c49806f1ef4cefc6f4558e21b9c1e3d0e14/classmods-1.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-28 08:16:34",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "hmohammad2520-org",
    "github_project": "classmods",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "python-dotenv",
            "specs": []
        },
        {
            "name": "pytest",
            "specs": []
        },
        {
            "name": "setuptools",
            "specs": []
        }
    ],
    "lcname": "classmods"
}
        
Elapsed time: 0.71039s