safemath


Namesafemath JSON
Version 1.0.0 PyPI version JSON
download
home_pageNone
SummaryBulletproof mathematical operations for Python with intelligent fallback handling
upload_time2025-08-06 20:17:14
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseMIT
keywords math safe numpy pandas division-by-zero
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # SafeMath ๐Ÿ›ก๏ธ

[![PyPI version](https://badge.fury.io/py/safemath.svg)](https://badge.fury.io/py/safemath)
[![Python Support](https://img.shields.io/pypi/pyversions/safemath.svg)](https://pypi.org/project/safemath/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**Production-ready safe mathematical operations that never crash.**

SafeMath provides robust mathematical functions that handle edge cases gracefully across Python scalars, NumPy arrays, Pandas Series, and DataFrames. Perfect for data science, financial calculations, and any application where mathematical reliability is crucial.

## ๐Ÿš€ Quick Start

pip install safemath


undefined
import safemath as sm
import numpy as np
import pandas as pd

Never crashes, returns fallback values instead
result = sm.safe_divide(10, 0) # Returns: nan
result = sm.safe_log(-1, fallback=0) # Returns: 0
result = sm.safe_sqrt([-1, 4, 9]) # Returns: [nan, 2.0, 3.0]

Works seamlessly with Pandas
df = pd.DataFrame({'a': [1, -1, 0], 'b': })
df['safe_ratio'] = sm.safe_divide(df['a'], df['b']) # No crashes on division by zero



## โœจ Key Features

- **๐Ÿ›ก๏ธ Never Crashes**: All functions handle edge cases with configurable fallbacks
- **๐Ÿ“Š Universal Compatibility**: Works with scalars, NumPy arrays, Pandas Series/DataFrames
- **โšก High Performance**: Vectorized operations using NumPy under the hood  
- **๐ŸŽฏ Production Ready**: Comprehensive error handling and logging
- **๐Ÿ”ง Flexible Fallbacks**: Global and per-function fallback strategies
- **๐Ÿ”— Method Chaining**: Fluent API with SafeNumber wrapper
- **๐Ÿ“ Expression Evaluation**: Safe evaluation of mathematical expressions

## ๐Ÿ“š Complete Function Reference

### Arithmetic Operations
safe_add(a, b) # Addition with overflow protection
safe_subtract(a, b) # Subtraction
safe_multiply(a, b) # Multiplication
safe_divide(a, b) # Division (handles division by zero)
safe_mod(a, b) # Modulo operation
safe_power(a, b) # Exponentiation
safe_abs(x) # Absolute value
safe_negate(x) # Negation



### Mathematical Functions  
safe_log(x) # Natural logarithm
safe_log10(x) # Base-10 logarithm
safe_sqrt(x) # Square root
safe_sin(x) # Sine (radians)
safe_cos(x) # Cosine (radians)
safe_tan(x) # Tangent (radians)



## ๐Ÿ’ก Usage Examples

### Basic Operations
import safemath as sm

Scalars
result = sm.safe_divide(10, 0) # nan instead of ZeroDivisionError
result = sm.safe_log(-5, fallback=0) # 0 instead of ValueError

Arrays
import numpy as np
data = np.array([1, -1, 0, 4])
result = sm.safe_sqrt(data) # [1.0, nan, 0.0, 2.0]



### Pandas Integration
import pandas as pd

df = pd.DataFrame({
'revenue': ,
'costs': ,
'temperature': [25, -10, 0, 35]
})

Safe operations on columns
df['profit_margin'] = sm.safe_divide(df['revenue'] - df['costs'], df['revenue'])
df['log_temp'] = sm.safe_log(df['temperature'] + 273.15) # Convert to Kelvin first

In-place operations
sm.safe_sqrt(df[['revenue', 'costs']], inplace=True)



### Global Fallback Configuration
Set global fallback for all operations
sm.set_global_fallback(0)
result = sm.safe_log(-1) # Returns 0 instead of nan

Enable logging to track fallback usage
sm.enable_trace()
result = sm.safe_divide(10, 0) # Logs the fallback usage



### Method Chaining with SafeNumber
from safemath import SafeNumber

Fluent API for complex calculations
data = [16, -4, 0, 25]
result = SafeNumber(data).abs().sqrt().log().value_or(0)

Equivalent to: log(sqrt(abs(data))) with fallback 0


### Safe Expression Evaluation
Evaluate expressions safely
result = sm.safe_eval("log(x) + sqrt(y)", {"x": 10, "y": 25})

With fallback for invalid operations
result = sm.safe_eval("log(-1) + tan(pi/2)", fallback=0)

Works with arrays and DataFrames too
df = pd.DataFrame({'x': [1, -1, 0], 'y': })
result = sm.safe_eval("sqrt(x) + log(y)", df.to_dict('series'))



### Custom Fallback Strategies  
Per-function fallbacks
profit_margin = sm.safe_divide(profit, revenue, fallback=0.0)
log_values = sm.safe_log(data, fallback=-999)

Function decorator for custom functions
@sm.safe_function(fallback=0)
def complex_calculation(x):
return np.log(x) / np.sqrt(x - 1)

result = complex_calculation() # Handles all edge cases



## ๐Ÿงช Error Handling Examples

All of these return sensible fallbacks instead of crashing:
sm.safe_divide(1, 0) # nan (division by zero)
sm.safe_log(-1) # nan (negative logarithm)
sm.safe_sqrt([-1, 4]) # [nan, 2.0] (negative sqrt)
sm.safe_tan(np.pi/2) # finite value (domain error)
sm.safe_power(10, 1000) # handles overflow
sm.safe_add(None, 5) # nan (None input)

Custom fallbacks
sm.safe_log(0, fallback=-np.inf) # -inf instead of nan
sm.safe_divide(, 0, fallback=999) #



## ๐Ÿ—๏ธ Advanced Usage

### Command Line Interface
Evaluate expressions from command line
safemath "log(10) + sqrt(25)" --fallback=0
safemath "x^2 + y" --variables="x=3" --variables="y=4"



### Integration with Existing Code
Replace standard operations
import numpy as np
import safemath as sm

Instead of:
result = np.log(data) / np.sqrt(data - 1) # Can crash
Use:
result = sm.safe_divide(sm.safe_log(data), sm.safe_sqrt(data - 1))

Or with method chaining:
result = SafeNumber(data).log().divide(SafeNumber(data - 1).sqrt()).value()



### Performance Considerations
SafeMath is optimized for production use:
- Vectorized NumPy operations for arrays
- Minimal overhead for scalar operations  
- Efficient fallback handling
- Optional tracing that can be disabled in production

## ๐Ÿ“Š Supported Data Types

| Input Type | Example | Output Type |
|------------|---------|-------------|  
| Scalar | `5`, `3.14`, `1+2j` | Same type |
| List/Tuple | `[1, 2, 3]` | NumPy array |
| NumPy Array | `np.array([1, 2, 3])` | NumPy array |
| Pandas Series | `pd.Series([1, 2, 3])` | Pandas Series |
| Pandas DataFrame | Numeric columns only | Pandas DataFrame |

## ๐Ÿ”ง Configuration Options

Global fallback value
sm.set_global_fallback(0) # Use 0 instead of nan
sm.set_global_fallback(None) # Use None for errors
sm.set_global_fallback(-999) # Custom error code

Logging and tracing
sm.enable_trace() # Log all fallback usage
sm.disable_trace() # Disable logging

Check current settings
current_fallback = sm.get_global_fallback()



## ๐Ÿงช Testing

Run full test suite
python -m pytest tests/

With coverage
python -m pytest tests/ --cov=safemath

Run specific test modules
python -m pytest tests/test_core.py
python -m pytest tests/test_pandas.py



## ๐Ÿ“‹ Requirements

- Python >= 3.7
- NumPy >= 1.19.0  
- Pandas >= 1.3.0

## ๐Ÿ“„ License

MIT License - see [LICENSE](LICENSE) file for details.

## ๐Ÿค Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## ๐Ÿ”— Links

- [PyPI Package](https://pypi.org/project/safemath/)
- [GitHub Repository](https://github.com/username/safemath)
- [Documentation](https://github.com/username/safemath#readme)
- [Issue Tracker](https://github.com/username/safemath/issues)

## โญ Show your support  

Give a โญ๏ธ if this project helped you!

---

**SafeMath** - Making mathematical operations safe and reliable for production Python applications.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "safemath",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "math, safe, numpy, pandas, division-by-zero",
    "author": null,
    "author_email": "Aman Choudhary <aman.1727.2706@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/80/5d/b74673b2f48c40e74c6f5ed262dcb71fe22e14d88e084f1078d819d173e0/safemath-1.0.0.tar.gz",
    "platform": null,
    "description": "# SafeMath \ud83d\udee1\ufe0f\r\n\r\n[![PyPI version](https://badge.fury.io/py/safemath.svg)](https://badge.fury.io/py/safemath)\r\n[![Python Support](https://img.shields.io/pypi/pyversions/safemath.svg)](https://pypi.org/project/safemath/)\r\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\r\n\r\n**Production-ready safe mathematical operations that never crash.**\r\n\r\nSafeMath provides robust mathematical functions that handle edge cases gracefully across Python scalars, NumPy arrays, Pandas Series, and DataFrames. Perfect for data science, financial calculations, and any application where mathematical reliability is crucial.\r\n\r\n## \ud83d\ude80 Quick Start\r\n\r\npip install safemath\r\n\r\n\r\nundefined\r\nimport safemath as sm\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nNever crashes, returns fallback values instead\r\nresult = sm.safe_divide(10, 0) # Returns: nan\r\nresult = sm.safe_log(-1, fallback=0) # Returns: 0\r\nresult = sm.safe_sqrt([-1, 4, 9]) # Returns: [nan, 2.0, 3.0]\r\n\r\nWorks seamlessly with Pandas\r\ndf = pd.DataFrame({'a': [1, -1, 0], 'b': })\r\ndf['safe_ratio'] = sm.safe_divide(df['a'], df['b']) # No crashes on division by zero\r\n\r\n\r\n\r\n## \u2728 Key Features\r\n\r\n- **\ud83d\udee1\ufe0f Never Crashes**: All functions handle edge cases with configurable fallbacks\r\n- **\ud83d\udcca Universal Compatibility**: Works with scalars, NumPy arrays, Pandas Series/DataFrames\r\n- **\u26a1 High Performance**: Vectorized operations using NumPy under the hood  \r\n- **\ud83c\udfaf Production Ready**: Comprehensive error handling and logging\r\n- **\ud83d\udd27 Flexible Fallbacks**: Global and per-function fallback strategies\r\n- **\ud83d\udd17 Method Chaining**: Fluent API with SafeNumber wrapper\r\n- **\ud83d\udcdd Expression Evaluation**: Safe evaluation of mathematical expressions\r\n\r\n## \ud83d\udcda Complete Function Reference\r\n\r\n### Arithmetic Operations\r\nsafe_add(a, b) # Addition with overflow protection\r\nsafe_subtract(a, b) # Subtraction\r\nsafe_multiply(a, b) # Multiplication\r\nsafe_divide(a, b) # Division (handles division by zero)\r\nsafe_mod(a, b) # Modulo operation\r\nsafe_power(a, b) # Exponentiation\r\nsafe_abs(x) # Absolute value\r\nsafe_negate(x) # Negation\r\n\r\n\r\n\r\n### Mathematical Functions  \r\nsafe_log(x) # Natural logarithm\r\nsafe_log10(x) # Base-10 logarithm\r\nsafe_sqrt(x) # Square root\r\nsafe_sin(x) # Sine (radians)\r\nsafe_cos(x) # Cosine (radians)\r\nsafe_tan(x) # Tangent (radians)\r\n\r\n\r\n\r\n## \ud83d\udca1 Usage Examples\r\n\r\n### Basic Operations\r\nimport safemath as sm\r\n\r\nScalars\r\nresult = sm.safe_divide(10, 0) # nan instead of ZeroDivisionError\r\nresult = sm.safe_log(-5, fallback=0) # 0 instead of ValueError\r\n\r\nArrays\r\nimport numpy as np\r\ndata = np.array([1, -1, 0, 4])\r\nresult = sm.safe_sqrt(data) # [1.0, nan, 0.0, 2.0]\r\n\r\n\r\n\r\n### Pandas Integration\r\nimport pandas as pd\r\n\r\ndf = pd.DataFrame({\r\n'revenue': ,\r\n'costs': ,\r\n'temperature': [25, -10, 0, 35]\r\n})\r\n\r\nSafe operations on columns\r\ndf['profit_margin'] = sm.safe_divide(df['revenue'] - df['costs'], df['revenue'])\r\ndf['log_temp'] = sm.safe_log(df['temperature'] + 273.15) # Convert to Kelvin first\r\n\r\nIn-place operations\r\nsm.safe_sqrt(df[['revenue', 'costs']], inplace=True)\r\n\r\n\r\n\r\n### Global Fallback Configuration\r\nSet global fallback for all operations\r\nsm.set_global_fallback(0)\r\nresult = sm.safe_log(-1) # Returns 0 instead of nan\r\n\r\nEnable logging to track fallback usage\r\nsm.enable_trace()\r\nresult = sm.safe_divide(10, 0) # Logs the fallback usage\r\n\r\n\r\n\r\n### Method Chaining with SafeNumber\r\nfrom safemath import SafeNumber\r\n\r\nFluent API for complex calculations\r\ndata = [16, -4, 0, 25]\r\nresult = SafeNumber(data).abs().sqrt().log().value_or(0)\r\n\r\nEquivalent to: log(sqrt(abs(data))) with fallback 0\r\n\r\n\r\n### Safe Expression Evaluation\r\nEvaluate expressions safely\r\nresult = sm.safe_eval(\"log(x) + sqrt(y)\", {\"x\": 10, \"y\": 25})\r\n\r\nWith fallback for invalid operations\r\nresult = sm.safe_eval(\"log(-1) + tan(pi/2)\", fallback=0)\r\n\r\nWorks with arrays and DataFrames too\r\ndf = pd.DataFrame({'x': [1, -1, 0], 'y': })\r\nresult = sm.safe_eval(\"sqrt(x) + log(y)\", df.to_dict('series'))\r\n\r\n\r\n\r\n### Custom Fallback Strategies  \r\nPer-function fallbacks\r\nprofit_margin = sm.safe_divide(profit, revenue, fallback=0.0)\r\nlog_values = sm.safe_log(data, fallback=-999)\r\n\r\nFunction decorator for custom functions\r\n@sm.safe_function(fallback=0)\r\ndef complex_calculation(x):\r\nreturn np.log(x) / np.sqrt(x - 1)\r\n\r\nresult = complex_calculation() # Handles all edge cases\r\n\r\n\r\n\r\n## \ud83e\uddea Error Handling Examples\r\n\r\nAll of these return sensible fallbacks instead of crashing:\r\nsm.safe_divide(1, 0) # nan (division by zero)\r\nsm.safe_log(-1) # nan (negative logarithm)\r\nsm.safe_sqrt([-1, 4]) # [nan, 2.0] (negative sqrt)\r\nsm.safe_tan(np.pi/2) # finite value (domain error)\r\nsm.safe_power(10, 1000) # handles overflow\r\nsm.safe_add(None, 5) # nan (None input)\r\n\r\nCustom fallbacks\r\nsm.safe_log(0, fallback=-np.inf) # -inf instead of nan\r\nsm.safe_divide(, 0, fallback=999) #\r\n\r\n\r\n\r\n## \ud83c\udfd7\ufe0f Advanced Usage\r\n\r\n### Command Line Interface\r\nEvaluate expressions from command line\r\nsafemath \"log(10) + sqrt(25)\" --fallback=0\r\nsafemath \"x^2 + y\" --variables=\"x=3\" --variables=\"y=4\"\r\n\r\n\r\n\r\n### Integration with Existing Code\r\nReplace standard operations\r\nimport numpy as np\r\nimport safemath as sm\r\n\r\nInstead of:\r\nresult = np.log(data) / np.sqrt(data - 1) # Can crash\r\nUse:\r\nresult = sm.safe_divide(sm.safe_log(data), sm.safe_sqrt(data - 1))\r\n\r\nOr with method chaining:\r\nresult = SafeNumber(data).log().divide(SafeNumber(data - 1).sqrt()).value()\r\n\r\n\r\n\r\n### Performance Considerations\r\nSafeMath is optimized for production use:\r\n- Vectorized NumPy operations for arrays\r\n- Minimal overhead for scalar operations  \r\n- Efficient fallback handling\r\n- Optional tracing that can be disabled in production\r\n\r\n## \ud83d\udcca Supported Data Types\r\n\r\n| Input Type | Example | Output Type |\r\n|------------|---------|-------------|  \r\n| Scalar | `5`, `3.14`, `1+2j` | Same type |\r\n| List/Tuple | `[1, 2, 3]` | NumPy array |\r\n| NumPy Array | `np.array([1, 2, 3])` | NumPy array |\r\n| Pandas Series | `pd.Series([1, 2, 3])` | Pandas Series |\r\n| Pandas DataFrame | Numeric columns only | Pandas DataFrame |\r\n\r\n## \ud83d\udd27 Configuration Options\r\n\r\nGlobal fallback value\r\nsm.set_global_fallback(0) # Use 0 instead of nan\r\nsm.set_global_fallback(None) # Use None for errors\r\nsm.set_global_fallback(-999) # Custom error code\r\n\r\nLogging and tracing\r\nsm.enable_trace() # Log all fallback usage\r\nsm.disable_trace() # Disable logging\r\n\r\nCheck current settings\r\ncurrent_fallback = sm.get_global_fallback()\r\n\r\n\r\n\r\n## \ud83e\uddea Testing\r\n\r\nRun full test suite\r\npython -m pytest tests/\r\n\r\nWith coverage\r\npython -m pytest tests/ --cov=safemath\r\n\r\nRun specific test modules\r\npython -m pytest tests/test_core.py\r\npython -m pytest tests/test_pandas.py\r\n\r\n\r\n\r\n## \ud83d\udccb Requirements\r\n\r\n- Python >= 3.7\r\n- NumPy >= 1.19.0  \r\n- Pandas >= 1.3.0\r\n\r\n## \ud83d\udcc4 License\r\n\r\nMIT License - see [LICENSE](LICENSE) file for details.\r\n\r\n## \ud83e\udd1d Contributing\r\n\r\n1. Fork the repository\r\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\r\n3. Commit your changes (`git commit -m 'Add amazing feature'`)\r\n4. Push to the branch (`git push origin feature/amazing-feature`)\r\n5. Open a Pull Request\r\n\r\n## \ud83d\udd17 Links\r\n\r\n- [PyPI Package](https://pypi.org/project/safemath/)\r\n- [GitHub Repository](https://github.com/username/safemath)\r\n- [Documentation](https://github.com/username/safemath#readme)\r\n- [Issue Tracker](https://github.com/username/safemath/issues)\r\n\r\n## \u2b50 Show your support  \r\n\r\nGive a \u2b50\ufe0f if this project helped you!\r\n\r\n---\r\n\r\n**SafeMath** - Making mathematical operations safe and reliable for production Python applications.\r\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Bulletproof mathematical operations for Python with intelligent fallback handling",
    "version": "1.0.0",
    "project_urls": {
        "Homepage": "https://github.com/yourusername/safemath",
        "Repository": "https://github.com/yourusername/safemath"
    },
    "split_keywords": [
        "math",
        " safe",
        " numpy",
        " pandas",
        " division-by-zero"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "ab4c72cc00d4cdeb6e5663b4b192cfd7146b25935a45c12b85f28bd3fe0479ce",
                "md5": "c5ff00b29a25b290b16a77b005a92e3c",
                "sha256": "6a274bd7562ed3a434f79a9248121bf08394cb9475f9f6d722f48c7f0a77c125"
            },
            "downloads": -1,
            "filename": "safemath-1.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c5ff00b29a25b290b16a77b005a92e3c",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 14819,
            "upload_time": "2025-08-06T20:17:13",
            "upload_time_iso_8601": "2025-08-06T20:17:13.265380Z",
            "url": "https://files.pythonhosted.org/packages/ab/4c/72cc00d4cdeb6e5663b4b192cfd7146b25935a45c12b85f28bd3fe0479ce/safemath-1.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "805db74673b2f48c40e74c6f5ed262dcb71fe22e14d88e084f1078d819d173e0",
                "md5": "adc13d8fe71867347dabbf9a84f1a845",
                "sha256": "5c22036886374eaacb3f02d83d3b32bd3ef209584ccb1dea03b674810125de00"
            },
            "downloads": -1,
            "filename": "safemath-1.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "adc13d8fe71867347dabbf9a84f1a845",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 20580,
            "upload_time": "2025-08-06T20:17:14",
            "upload_time_iso_8601": "2025-08-06T20:17:14.813673Z",
            "url": "https://files.pythonhosted.org/packages/80/5d/b74673b2f48c40e74c6f5ed262dcb71fe22e14d88e084f1078d819d173e0/safemath-1.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-06 20:17:14",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "yourusername",
    "github_project": "safemath",
    "github_not_found": true,
    "lcname": "safemath"
}
        
Elapsed time: 2.14535s