pywraps


Namepywraps JSON
Version 1.0.1 PyPI version JSON
download
home_pageNone
SummaryA collection of powerful Python decorators for enhanced functionality
upload_time2025-08-04 19:33:32
maintainerNone
docs_urlNone
authorNone
requires_python>=3.7
licenseNone
keywords background debounce decorators functional-programming python retry timeout utilities
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            
<div align="center">

# PyWraps ๐ŸŽ

**A collection of powerful Python decorators for enhanced functionality**

[![PyPI version](https://badge.fury.io/py/pywraps.svg)](https://badge.fury.io/py/pywraps)
[![Python Support](https://img.shields.io/pypi/pyversions/pywraps.svg)](https://pypi.org/project/pywraps/)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![Code Quality](https://img.shields.io/badge/code%20quality-A+-brightgreen.svg)](https://github.com/pywraps/pywraps)

</div>

## ๐Ÿš€ Features

PyWraps provides a comprehensive suite of decorators that enhance your Python functions with powerful capabilities:

- **๐Ÿ”„ Retry**: Automatically retry failed function calls with customizable attempts and delays
- **โฑ๏ธ Timeout**: Set execution time limits for both synchronous and asynchronous functions
- **๐ŸŽฏ Debounce**: Prevent rapid successive function calls, executing only the last one
- **๐Ÿงต Background**: Execute functions in separate threads without blocking the main thread

## ๐Ÿ“ฆ Installation

```bash
pip install pywraps
```

## ๐ŸŽฏ Quick Start

```python
from pywraps import retry, timeout, debounce, background
import time
import random

@retry(tries=3, delay=1.0)
def unreliable_function():
    if random.random() < 0.7:
        raise Exception("Random failure!")
    return "Success!"

@timeout(seconds=5.0)
def slow_function():
    time.sleep(3)
    return "Completed within timeout"

@debounce(wait=2.0)
def search_function(query):
    print(f"Searching for: {query}")

@background
def heavy_computation():
    time.sleep(10)
    print("Background task completed!")
```

## ๐Ÿ“š Detailed Documentation

### ๐Ÿ”„ Retry Decorator

The `@retry` decorator automatically retries function execution when exceptions occur.

#### Parameters:
- `tries` (int): Number of retry attempts (default: 3)
- `delay` (float): Delay between retries in seconds (default: 1.0)
- `exceptions` (Exception or tuple): Exception types to catch (default: Exception)

#### Examples:

```python
from pywraps import retry
import requests
import random

@retry(tries=5, delay=2.0)
def fetch_data_from_api():
    response = requests.get("https://api.example.com/data")
    if response.status_code != 200:
        raise requests.RequestException("API request failed")
    return response.json()

@retry(tries=3, delay=0.5, exceptions=(ValueError, TypeError))
def parse_user_input(user_input):
    if not user_input.strip():
        raise ValueError("Empty input")
    return int(user_input)

@retry(tries=10, delay=1.0)
def database_operation():
    if random.random() < 0.8:
        raise ConnectionError("Database connection failed")
    return "Data saved successfully"

try:
    result = fetch_data_from_api()
    print("API data:", result)
except requests.RequestException as e:
    print(f"Failed after retries: {e}")
```

### โฑ๏ธ Timeout Decorator

The `@timeout` decorator sets execution time limits for functions, supporting both synchronous and asynchronous operations.

#### Parameters:
- `seconds` (float): Maximum execution time in seconds

#### Examples:

```python
from pywraps import timeout
import time
import asyncio
import aiohttp

@timeout(seconds=3.0)
def cpu_intensive_task():
    total = 0
    for i in range(10000000):
        total += i * i
    return total

@timeout(seconds=5.0)
async def fetch_multiple_urls():
    urls = [
        "https://httpbin.org/delay/1",
        "https://httpbin.org/delay/2",
        "https://httpbin.org/delay/1"
    ]
    
    async with aiohttp.ClientSession() as session:
        tasks = []
        for url in urls:
            tasks.append(session.get(url))
        
        responses = await asyncio.gather(*tasks)
        return [resp.status for resp in responses]

@timeout(seconds=2.0)
def file_processing():
    with open("large_file.txt", "r") as f:
        lines = f.readlines()
    return len(lines)

try:
    result = cpu_intensive_task()
    print("Task completed:", result)
except TimeoutError as e:
    print(f"Operation timed out: {e}")

async def main():
    try:
        statuses = await fetch_multiple_urls()
        print("HTTP statuses:", statuses)
    except TimeoutError as e:
        print(f"Async operation timed out: {e}")

asyncio.run(main())
```

### ๐ŸŽฏ Debounce Decorator

The `@debounce` decorator prevents rapid successive function calls, executing only the last call after a specified delay.

#### Parameters:
- `wait` (float): Delay time in seconds before execution

#### Examples:

```python
from pywraps import debounce
import time

@debounce(wait=1.0)
def save_user_preferences(user_id, preferences):
    print(f"Saving preferences for user {user_id}: {preferences}")
    

@debounce(wait=0.5)
def search_suggestions(query):
    print(f"Fetching suggestions for: '{query}'")
    return [f"{query}_suggestion_{i}" for i in range(3)]

@debounce(wait=2.0)
def auto_save_document(document_id, content):
    print(f"Auto-saving document {document_id}")
    with open(f"doc_{document_id}.txt", "w") as f:
        f.write(content)

user_prefs = {"theme": "dark", "language": "en"}
save_user_preferences(123, user_prefs)
save_user_preferences(123, {**user_prefs, "theme": "light"})
save_user_preferences(123, {**user_prefs, "notifications": True})

for query in ["py", "pyt", "pyth", "pytho", "python"]:
    search_suggestions(query)
    time.sleep(0.1)

time.sleep(3)
```

### ๐Ÿงต Background Decorator

The `@background` decorator executes functions in separate threads, preventing blocking of the main thread.

#### Examples:

```python
from pywraps import background
import time
import logging

logging.basicConfig(level=logging.INFO)

@background
def send_email_notification(recipient, subject, body):
    print(f"Sending email to {recipient}...")
    time.sleep(2)
    print(f"Email sent to {recipient}: {subject}")

@background
def generate_report(report_type, data):
    print(f"Generating {report_type} report...")
    time.sleep(5)
    print(f"Report '{report_type}' generated with {len(data)} records")

@background
def cleanup_temp_files():
    print("Starting cleanup process...")
    time.sleep(3)
    print("Temporary files cleaned up")

@background
def log_user_activity(user_id, action, timestamp):
    logging.info(f"User {user_id} performed {action} at {timestamp}")
    time.sleep(0.5)
    logging.info(f"Activity logged for user {user_id}")

send_email_notification("user@example.com", "Welcome!", "Thank you for joining!")
generate_report("monthly_sales", list(range(1000)))
cleanup_temp_files()

for i in range(5):
    log_user_activity(f"user_{i}", "login", time.time())

print("All background tasks started!")
time.sleep(6)
print("Main thread continues...")
```

## ๐Ÿ”ง Advanced Usage

### Combining Decorators

You can combine multiple decorators for enhanced functionality:

```python
from pywraps import retry, timeout, background
import requests
import time

@background
@retry(tries=3, delay=1.0)
@timeout(seconds=10.0)
def robust_api_call(url):
    response = requests.get(url)
    response.raise_for_status()
    return response.json()

@retry(tries=5, delay=0.5)
@timeout(seconds=30.0)
def critical_database_operation():
    time.sleep(2)
    return "Operation completed successfully"

robust_api_call("https://api.github.com/users/octocat")
result = critical_database_operation()
print(result)
```

### Error Handling Best Practices

```python
from pywraps import retry, timeout
import logging

logging.basicConfig(level=logging.INFO)

@retry(tries=3, delay=1.0, exceptions=(ConnectionError, TimeoutError))
@timeout(seconds=5.0)
def resilient_operation():
    import random
    if random.random() < 0.6:
        raise ConnectionError("Network issue")
    return "Success"

try:
    result = resilient_operation()
    logging.info(f"Operation successful: {result}")
except Exception as e:
    logging.error(f"Operation failed after all retries: {e}")
```

## ๐ŸŽจ Use Cases

### Web Development
- **API Rate Limiting**: Use `@debounce` for search endpoints
- **Timeout Protection**: Apply `@timeout` to external API calls
- **Background Processing**: Use `@background` for email sending, file uploads
- **Retry Logic**: Implement `@retry` for database operations

### Data Processing
- **Batch Operations**: `@background` for large dataset processing
- **Network Resilience**: `@retry` for data fetching from unreliable sources
- **Resource Management**: `@timeout` to prevent memory leaks in long operations

### User Interface
- **Search Optimization**: `@debounce` for real-time search suggestions
- **Form Validation**: `@debounce` for input validation
- **Progress Tracking**: `@background` for long-running tasks with progress updates

## ๐Ÿค Contributing

We welcome contributions! Here's how you can help:

1. Fork the repository
2. Create a feature branch: `git checkout -b feature-name`
3. Make your changes and add tests
4. Commit your changes: `git commit -am 'Add new feature'`
5. Push to the branch: `git push origin feature-name`
6. Submit a pull request

## ๐Ÿ“„ License

This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ™ Acknowledgments

- Inspired by the need for simple, powerful decorators in Python
- Built with love for the Python community
- Special thanks to all contributors and users

---

<div align="center">

**Made with โค๏ธ by the [firatmio](https://github.com/firatmio)**

[โญ Star us on GitHub](https://github.com/firatmio/pywraps) | [๐Ÿ› Report Issues](https://github.com/firatmio/pywraps/issues) | [๐Ÿ“– Documentation](https://github.com/firatmio/pywraps#readme)

</div>
            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "pywraps",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "firatmio <firattunaarslan@gmail.com>",
    "keywords": "background, debounce, decorators, functional-programming, python, retry, timeout, utilities",
    "author": null,
    "author_email": "firatmio <firattunaarslan@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/ee/aa/7a28b7e943bf0b2bdab734872fa4818cd1663643189058a7c23187213e75/pywraps-1.0.1.tar.gz",
    "platform": null,
    "description": "\n<div align=\"center\">\n\n# PyWraps \ud83c\udf81\n\n**A collection of powerful Python decorators for enhanced functionality**\n\n[![PyPI version](https://badge.fury.io/py/pywraps.svg)](https://badge.fury.io/py/pywraps)\n[![Python Support](https://img.shields.io/pypi/pyversions/pywraps.svg)](https://pypi.org/project/pywraps/)\n[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)\n[![Code Quality](https://img.shields.io/badge/code%20quality-A+-brightgreen.svg)](https://github.com/pywraps/pywraps)\n\n</div>\n\n## \ud83d\ude80 Features\n\nPyWraps provides a comprehensive suite of decorators that enhance your Python functions with powerful capabilities:\n\n- **\ud83d\udd04 Retry**: Automatically retry failed function calls with customizable attempts and delays\n- **\u23f1\ufe0f Timeout**: Set execution time limits for both synchronous and asynchronous functions\n- **\ud83c\udfaf Debounce**: Prevent rapid successive function calls, executing only the last one\n- **\ud83e\uddf5 Background**: Execute functions in separate threads without blocking the main thread\n\n## \ud83d\udce6 Installation\n\n```bash\npip install pywraps\n```\n\n## \ud83c\udfaf Quick Start\n\n```python\nfrom pywraps import retry, timeout, debounce, background\nimport time\nimport random\n\n@retry(tries=3, delay=1.0)\ndef unreliable_function():\n    if random.random() < 0.7:\n        raise Exception(\"Random failure!\")\n    return \"Success!\"\n\n@timeout(seconds=5.0)\ndef slow_function():\n    time.sleep(3)\n    return \"Completed within timeout\"\n\n@debounce(wait=2.0)\ndef search_function(query):\n    print(f\"Searching for: {query}\")\n\n@background\ndef heavy_computation():\n    time.sleep(10)\n    print(\"Background task completed!\")\n```\n\n## \ud83d\udcda Detailed Documentation\n\n### \ud83d\udd04 Retry Decorator\n\nThe `@retry` decorator automatically retries function execution when exceptions occur.\n\n#### Parameters:\n- `tries` (int): Number of retry attempts (default: 3)\n- `delay` (float): Delay between retries in seconds (default: 1.0)\n- `exceptions` (Exception or tuple): Exception types to catch (default: Exception)\n\n#### Examples:\n\n```python\nfrom pywraps import retry\nimport requests\nimport random\n\n@retry(tries=5, delay=2.0)\ndef fetch_data_from_api():\n    response = requests.get(\"https://api.example.com/data\")\n    if response.status_code != 200:\n        raise requests.RequestException(\"API request failed\")\n    return response.json()\n\n@retry(tries=3, delay=0.5, exceptions=(ValueError, TypeError))\ndef parse_user_input(user_input):\n    if not user_input.strip():\n        raise ValueError(\"Empty input\")\n    return int(user_input)\n\n@retry(tries=10, delay=1.0)\ndef database_operation():\n    if random.random() < 0.8:\n        raise ConnectionError(\"Database connection failed\")\n    return \"Data saved successfully\"\n\ntry:\n    result = fetch_data_from_api()\n    print(\"API data:\", result)\nexcept requests.RequestException as e:\n    print(f\"Failed after retries: {e}\")\n```\n\n### \u23f1\ufe0f Timeout Decorator\n\nThe `@timeout` decorator sets execution time limits for functions, supporting both synchronous and asynchronous operations.\n\n#### Parameters:\n- `seconds` (float): Maximum execution time in seconds\n\n#### Examples:\n\n```python\nfrom pywraps import timeout\nimport time\nimport asyncio\nimport aiohttp\n\n@timeout(seconds=3.0)\ndef cpu_intensive_task():\n    total = 0\n    for i in range(10000000):\n        total += i * i\n    return total\n\n@timeout(seconds=5.0)\nasync def fetch_multiple_urls():\n    urls = [\n        \"https://httpbin.org/delay/1\",\n        \"https://httpbin.org/delay/2\",\n        \"https://httpbin.org/delay/1\"\n    ]\n    \n    async with aiohttp.ClientSession() as session:\n        tasks = []\n        for url in urls:\n            tasks.append(session.get(url))\n        \n        responses = await asyncio.gather(*tasks)\n        return [resp.status for resp in responses]\n\n@timeout(seconds=2.0)\ndef file_processing():\n    with open(\"large_file.txt\", \"r\") as f:\n        lines = f.readlines()\n    return len(lines)\n\ntry:\n    result = cpu_intensive_task()\n    print(\"Task completed:\", result)\nexcept TimeoutError as e:\n    print(f\"Operation timed out: {e}\")\n\nasync def main():\n    try:\n        statuses = await fetch_multiple_urls()\n        print(\"HTTP statuses:\", statuses)\n    except TimeoutError as e:\n        print(f\"Async operation timed out: {e}\")\n\nasyncio.run(main())\n```\n\n### \ud83c\udfaf Debounce Decorator\n\nThe `@debounce` decorator prevents rapid successive function calls, executing only the last call after a specified delay.\n\n#### Parameters:\n- `wait` (float): Delay time in seconds before execution\n\n#### Examples:\n\n```python\nfrom pywraps import debounce\nimport time\n\n@debounce(wait=1.0)\ndef save_user_preferences(user_id, preferences):\n    print(f\"Saving preferences for user {user_id}: {preferences}\")\n    \n\n@debounce(wait=0.5)\ndef search_suggestions(query):\n    print(f\"Fetching suggestions for: '{query}'\")\n    return [f\"{query}_suggestion_{i}\" for i in range(3)]\n\n@debounce(wait=2.0)\ndef auto_save_document(document_id, content):\n    print(f\"Auto-saving document {document_id}\")\n    with open(f\"doc_{document_id}.txt\", \"w\") as f:\n        f.write(content)\n\nuser_prefs = {\"theme\": \"dark\", \"language\": \"en\"}\nsave_user_preferences(123, user_prefs)\nsave_user_preferences(123, {**user_prefs, \"theme\": \"light\"})\nsave_user_preferences(123, {**user_prefs, \"notifications\": True})\n\nfor query in [\"py\", \"pyt\", \"pyth\", \"pytho\", \"python\"]:\n    search_suggestions(query)\n    time.sleep(0.1)\n\ntime.sleep(3)\n```\n\n### \ud83e\uddf5 Background Decorator\n\nThe `@background` decorator executes functions in separate threads, preventing blocking of the main thread.\n\n#### Examples:\n\n```python\nfrom pywraps import background\nimport time\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\n\n@background\ndef send_email_notification(recipient, subject, body):\n    print(f\"Sending email to {recipient}...\")\n    time.sleep(2)\n    print(f\"Email sent to {recipient}: {subject}\")\n\n@background\ndef generate_report(report_type, data):\n    print(f\"Generating {report_type} report...\")\n    time.sleep(5)\n    print(f\"Report '{report_type}' generated with {len(data)} records\")\n\n@background\ndef cleanup_temp_files():\n    print(\"Starting cleanup process...\")\n    time.sleep(3)\n    print(\"Temporary files cleaned up\")\n\n@background\ndef log_user_activity(user_id, action, timestamp):\n    logging.info(f\"User {user_id} performed {action} at {timestamp}\")\n    time.sleep(0.5)\n    logging.info(f\"Activity logged for user {user_id}\")\n\nsend_email_notification(\"user@example.com\", \"Welcome!\", \"Thank you for joining!\")\ngenerate_report(\"monthly_sales\", list(range(1000)))\ncleanup_temp_files()\n\nfor i in range(5):\n    log_user_activity(f\"user_{i}\", \"login\", time.time())\n\nprint(\"All background tasks started!\")\ntime.sleep(6)\nprint(\"Main thread continues...\")\n```\n\n## \ud83d\udd27 Advanced Usage\n\n### Combining Decorators\n\nYou can combine multiple decorators for enhanced functionality:\n\n```python\nfrom pywraps import retry, timeout, background\nimport requests\nimport time\n\n@background\n@retry(tries=3, delay=1.0)\n@timeout(seconds=10.0)\ndef robust_api_call(url):\n    response = requests.get(url)\n    response.raise_for_status()\n    return response.json()\n\n@retry(tries=5, delay=0.5)\n@timeout(seconds=30.0)\ndef critical_database_operation():\n    time.sleep(2)\n    return \"Operation completed successfully\"\n\nrobust_api_call(\"https://api.github.com/users/octocat\")\nresult = critical_database_operation()\nprint(result)\n```\n\n### Error Handling Best Practices\n\n```python\nfrom pywraps import retry, timeout\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\n\n@retry(tries=3, delay=1.0, exceptions=(ConnectionError, TimeoutError))\n@timeout(seconds=5.0)\ndef resilient_operation():\n    import random\n    if random.random() < 0.6:\n        raise ConnectionError(\"Network issue\")\n    return \"Success\"\n\ntry:\n    result = resilient_operation()\n    logging.info(f\"Operation successful: {result}\")\nexcept Exception as e:\n    logging.error(f\"Operation failed after all retries: {e}\")\n```\n\n## \ud83c\udfa8 Use Cases\n\n### Web Development\n- **API Rate Limiting**: Use `@debounce` for search endpoints\n- **Timeout Protection**: Apply `@timeout` to external API calls\n- **Background Processing**: Use `@background` for email sending, file uploads\n- **Retry Logic**: Implement `@retry` for database operations\n\n### Data Processing\n- **Batch Operations**: `@background` for large dataset processing\n- **Network Resilience**: `@retry` for data fetching from unreliable sources\n- **Resource Management**: `@timeout` to prevent memory leaks in long operations\n\n### User Interface\n- **Search Optimization**: `@debounce` for real-time search suggestions\n- **Form Validation**: `@debounce` for input validation\n- **Progress Tracking**: `@background` for long-running tasks with progress updates\n\n## \ud83e\udd1d Contributing\n\nWe welcome contributions! Here's how you can help:\n\n1. Fork the repository\n2. Create a feature branch: `git checkout -b feature-name`\n3. Make your changes and add tests\n4. Commit your changes: `git commit -am 'Add new feature'`\n5. Push to the branch: `git push origin feature-name`\n6. Submit a pull request\n\n## \ud83d\udcc4 License\n\nThis project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.\n\n## \ud83d\ude4f Acknowledgments\n\n- Inspired by the need for simple, powerful decorators in Python\n- Built with love for the Python community\n- Special thanks to all contributors and users\n\n---\n\n<div align=\"center\">\n\n**Made with \u2764\ufe0f by the [firatmio](https://github.com/firatmio)**\n\n[\u2b50 Star us on GitHub](https://github.com/firatmio/pywraps) | [\ud83d\udc1b Report Issues](https://github.com/firatmio/pywraps/issues) | [\ud83d\udcd6 Documentation](https://github.com/firatmio/pywraps#readme)\n\n</div>",
    "bugtrack_url": null,
    "license": null,
    "summary": "A collection of powerful Python decorators for enhanced functionality",
    "version": "1.0.1",
    "project_urls": {
        "Bug Tracker": "https://github.com/firatmio/pywraps/issues",
        "Documentation": "https://github.com/firatmio/pywraps#readme",
        "Homepage": "https://github.com/firatmio/pywraps",
        "Repository": "https://github.com/firatmio/pywraps.git"
    },
    "split_keywords": [
        "background",
        " debounce",
        " decorators",
        " functional-programming",
        " python",
        " retry",
        " timeout",
        " utilities"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "0488e2e1841f9a6d8c8f4ab8e0d335b4ff236655232e5a9292937d8e78414941",
                "md5": "46c232a2ec388f76266fd1a06808f242",
                "sha256": "52c8f3555646b1b4978fdcf0dd003af2675d062f9eeac8bf6ece2c093f4eb7ae"
            },
            "downloads": -1,
            "filename": "pywraps-1.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "46c232a2ec388f76266fd1a06808f242",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 10919,
            "upload_time": "2025-08-04T19:33:30",
            "upload_time_iso_8601": "2025-08-04T19:33:30.248295Z",
            "url": "https://files.pythonhosted.org/packages/04/88/e2e1841f9a6d8c8f4ab8e0d335b4ff236655232e5a9292937d8e78414941/pywraps-1.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "eeaa7a28b7e943bf0b2bdab734872fa4818cd1663643189058a7c23187213e75",
                "md5": "76e354b8c669b8e2b1a2b222fc62fa65",
                "sha256": "77f21a5dc48ebed59c5996cee840cc35eace12aeb4cfe0c64be918bedef73e1d"
            },
            "downloads": -1,
            "filename": "pywraps-1.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "76e354b8c669b8e2b1a2b222fc62fa65",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 49688,
            "upload_time": "2025-08-04T19:33:32",
            "upload_time_iso_8601": "2025-08-04T19:33:32.095619Z",
            "url": "https://files.pythonhosted.org/packages/ee/aa/7a28b7e943bf0b2bdab734872fa4818cd1663643189058a7c23187213e75/pywraps-1.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-04 19:33:32",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "firatmio",
    "github_project": "pywraps",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "pywraps"
}
        
Elapsed time: 0.93433s