
<div align="center">
# byteunit
[](https://python.org)
[](https://opensource.org/licenses/MIT)
[](https://mypy.readthedocs.io/)
</div>
## Features
- 📦 **Comprehensive Unit Support**: Binary (KiB, MiB, GiB...), decimal (KB, MB, GB...), and bit units
- 🧮 **Smart Arithmetic Support**: Same-unit operations preserve units (1 GB + 2 GB = 3 GB), mixed units convert automatically
- 🎯 **Configurable Precision**: Eliminate scientific notation with configurable decimal precision (no more 1.23e-05 GB!)
- 📝 **Flexible String Parsing**: Case-insensitive parsing with support for various formats and separators
- 🔗 **Cross-Platform File Operations**: Get file and directory sizes using `pathlib` with platform-specific optimizations
- ⚡ **Platform-Specific Optimizations**: Windows, Linux, and macOS-specific implementations for better performance
- 🔒 **Type Safety**: Complete type annotations for better IDE support and code safety
- 🎯 **Zero Dependencies**: Uses only Python standard library
## Installation
```bash
pip install byteunit
```
## Quick Start
```python
from byteunit import Storage, StorageUnit, ByteUnit
# Create storage values
storage1 = Storage(1, StorageUnit.KIB)
storage2 = Storage(512, StorageUnit.BYTES)
# ByteUnit is an alias for Storage - both are functionally identical
byte_unit = ByteUnit(1024, StorageUnit.BYTES)
print(storage1 == byte_unit) # True
# Smart arithmetic - same units preserve unit, mixed units convert to bytes
same_unit_total = Storage(1, StorageUnit.GB) + Storage(2, StorageUnit.GB) # 3 GB (preserved!)
mixed_unit_total = storage1 + storage2 # 1536 BYTES (converted)
doubled = storage1 * 2 # 2 KIB
# Comparisons
print(storage1 > storage2) # True
print(storage1 == Storage(1024, StorageUnit.BYTES)) # True
# Unit conversion
print(storage1.convert_to_bytes()) # 1024.0
print(storage2.convert_to(StorageUnit.KIB)) # 0.5 KIB
# String parsing (flexible formats)
size1 = Storage.parse("1.5 MB") # 1.5 MB
size2 = Storage.parse("1,024 KiB") # 1024.0 KIB (comma as decimal separator)
size3 = Storage.parse("500GB") # 500.0 GB (no space)
size4 = Storage.parse("2.5 tb") # 2.5 TB (case insensitive)
size5 = Storage.parse("1024") # 1024.0 BYTES (defaults to bytes)
# Auto-scaling for human-readable output
large_size = Storage(1536000000, StorageUnit.BYTES)
print(large_size.auto_scale()) # 1.43 GIB (binary) or 1.536 GB (decimal)
# Decimal precision control (eliminates scientific notation)
Storage.set_decimal_precision(5) # Configure precision globally
small_value = Storage(9.872019291e-05, StorageUnit.GIB)
print(f"Precise: {small_value}") # 0.0001 GIB (no scientific notation!)
# File operations
file_size = Storage.get_size_from_path("/path/to/file.txt")
dir_size = Storage.get_size_from_path("/path/to/directory")
print(f"Directory size: {dir_size.auto_scale()}")
```
## Supported Units
### Binary Units (Base 1024)
- `BYTES` (1 byte)
- `KIB` (1,024 bytes)
- `MIB` (1,048,576 bytes)
- `GIB`, `TIB`, `PIB`, `EIB`, `ZIB`, `YIB`
### Decimal Units (Base 1000)
- `KB` (1,000 bytes)
- `MB` (1,000,000 bytes)
- `GB` (1,000,000,000 bytes)
- `TB`, `PB`, `EB`, `ZB`, `YB`
### Bit Units
- `BITS` (1/8 byte)
- `KILOBITS`, `MEGABITS`, `GIGABITS`, `TERABITS`, `PETABITS`, `EXABITS`, `ZETTABITS`, `YOTTABITS`
## Advanced Usage
### Platform-Specific Optimizations
```python
from byteunit import Storage
# Automatically detect and use platform-specific optimizations
platform_storage = Storage.get_platform_storage()
size = platform_storage.get_size_from_path("/large/directory")
# Platform info
info = platform_storage.get_platform_info()
print(f"Platform: {info['platform']}")
print(f"Optimizations: {info.get('api_optimization', 'none')}")
```
### String Parsing Features
The `parse()` method supports various input formats:
```python
from byteunit import Storage, StorageUnit
# Case insensitive
Storage.parse("1.5 mb") # Works
Storage.parse("1.5 MB") # Works
Storage.parse("1.5 Mb") # Works
# Decimal separators
Storage.parse("1.5 MB") # Dot separator
Storage.parse("1,5 MB") # Comma separator
# Spacing
Storage.parse("1.5 MB") # With space
Storage.parse("1.5MB") # Without space
# Default unit
Storage.parse("1024") # Defaults to bytes
Storage.parse("1024", StorageUnit.KIB) # Custom default
# Comprehensive unit aliases
Storage.parse("1 kilobyte") # Full name
Storage.parse("1 kb") # Abbreviation
Storage.parse("1 k") # Single letter
```
### Error Handling
```python
from byteunit import Storage, StorageUnit
# Invalid values raise appropriate exceptions
try:
Storage(-1, StorageUnit.BYTES) # Raises ValueError
except ValueError as e:
print(f"Error: {e}")
try:
Storage.parse("invalid") # Raises ValueError
except ValueError as e:
print(f"Parsing error: {e}")
try:
storage = Storage(1, StorageUnit.KIB)
result = storage / 0 # Raises ZeroDivisionError
except ZeroDivisionError as e:
print(f"Division error: {e}")
```
## Real-World Examples
### Download Time Calculator
ByteUnit is the same thing as Storage, so you can use either interchangeably.
```python
from byteunit import ByteUnit
# File sizes
movie = ByteUnit.parse("1.4 GB")
song = ByteUnit.parse("4.5 MB")
# Network speeds (in bits per second)
broadband = ByteUnit.parse("50 Megabits") # 50 Mbps
fiber = ByteUnit.parse("1 Gigabit") # 1 Gbps
# Calculate download times
movie_time_broadband = movie / broadband # seconds
movie_time_fiber = movie / fiber # seconds
print(f"Movie download time:")
print(f" Broadband (50 Mbps): {movie_time_broadband:.1f} seconds")
print(f" Fiber (1 Gbps): {movie_time_fiber:.1f} seconds")
```
### Storage Capacity Planning
```python
from byteunit import ByteUnit
# Calculate total storage needs
photos = ByteUnit.parse("2.8 MiB") * 2000 # 2000 photos
music = ByteUnit.parse("4.5 MB") * 500 # 500 songs
videos = ByteUnit.parse("1.2 GB") * 50 # 50 videos
documents = ByteUnit.parse("250 KB") * 1000 # 1000 documents
total_needed = photos + music + videos + documents
print(f"Total storage needed: {total_needed.auto_scale()}")
# Available storage
available = ByteUnit.parse("500 GB")
remaining = available - total_needed
print(f"Remaining space: {remaining.auto_scale()}")
```
## Development
### Running Tests
```bash
# Run basic functionality tests
python test_basic_functionality.py
```
### Building and Installation
please install uv first
```bash
# Install development dependencies
uv sync
```
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
Raw data
{
"_id": null,
"home_page": null,
"name": "filesizelib",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.9",
"maintainer_email": "PythonImporter <271374667@qq.com>",
"keywords": "bytes, conversion, cross-platform, file-size, pathlib, storage, units",
"author": null,
"author_email": "PythonImporter <271374667@qq.com>",
"download_url": "https://files.pythonhosted.org/packages/57/be/86cc53a315f2486945772f747e5965219a95a6bc548861f877973ca7e8a0/filesizelib-0.6.4.tar.gz",
"platform": null,
"description": "\n\n\n<div align=\"center\">\n\n# byteunit\n\n[](https://python.org)\n[](https://opensource.org/licenses/MIT)\n[](https://mypy.readthedocs.io/)\n\n</div>\n\n## Features\n\n- \ud83d\udce6 **Comprehensive Unit Support**: Binary (KiB, MiB, GiB...), decimal (KB, MB, GB...), and bit units\n- \ud83e\uddee **Smart Arithmetic Support**: Same-unit operations preserve units (1 GB + 2 GB = 3 GB), mixed units convert automatically\n- \ud83c\udfaf **Configurable Precision**: Eliminate scientific notation with configurable decimal precision (no more 1.23e-05 GB!)\n- \ud83d\udcdd **Flexible String Parsing**: Case-insensitive parsing with support for various formats and separators\n- \ud83d\udd17 **Cross-Platform File Operations**: Get file and directory sizes using `pathlib` with platform-specific optimizations\n- \u26a1 **Platform-Specific Optimizations**: Windows, Linux, and macOS-specific implementations for better performance\n- \ud83d\udd12 **Type Safety**: Complete type annotations for better IDE support and code safety\n- \ud83c\udfaf **Zero Dependencies**: Uses only Python standard library\n\n## Installation\n\n```bash\npip install byteunit\n```\n\n## Quick Start\n\n```python\nfrom byteunit import Storage, StorageUnit, ByteUnit\n\n# Create storage values\nstorage1 = Storage(1, StorageUnit.KIB)\nstorage2 = Storage(512, StorageUnit.BYTES)\n\n# ByteUnit is an alias for Storage - both are functionally identical\nbyte_unit = ByteUnit(1024, StorageUnit.BYTES)\nprint(storage1 == byte_unit) # True\n\n# Smart arithmetic - same units preserve unit, mixed units convert to bytes\nsame_unit_total = Storage(1, StorageUnit.GB) + Storage(2, StorageUnit.GB) # 3 GB (preserved!)\nmixed_unit_total = storage1 + storage2 # 1536 BYTES (converted)\ndoubled = storage1 * 2 # 2 KIB\n\n# Comparisons\nprint(storage1 > storage2) # True\nprint(storage1 == Storage(1024, StorageUnit.BYTES)) # True\n\n# Unit conversion\nprint(storage1.convert_to_bytes()) # 1024.0\nprint(storage2.convert_to(StorageUnit.KIB)) # 0.5 KIB\n\n# String parsing (flexible formats)\nsize1 = Storage.parse(\"1.5 MB\") # 1.5 MB\nsize2 = Storage.parse(\"1,024 KiB\") # 1024.0 KIB (comma as decimal separator)\nsize3 = Storage.parse(\"500GB\") # 500.0 GB (no space)\nsize4 = Storage.parse(\"2.5 tb\") # 2.5 TB (case insensitive)\nsize5 = Storage.parse(\"1024\") # 1024.0 BYTES (defaults to bytes)\n\n# Auto-scaling for human-readable output\nlarge_size = Storage(1536000000, StorageUnit.BYTES)\nprint(large_size.auto_scale()) # 1.43 GIB (binary) or 1.536 GB (decimal)\n\n# Decimal precision control (eliminates scientific notation)\nStorage.set_decimal_precision(5) # Configure precision globally\nsmall_value = Storage(9.872019291e-05, StorageUnit.GIB)\nprint(f\"Precise: {small_value}\") # 0.0001 GIB (no scientific notation!)\n\n# File operations\nfile_size = Storage.get_size_from_path(\"/path/to/file.txt\")\ndir_size = Storage.get_size_from_path(\"/path/to/directory\")\nprint(f\"Directory size: {dir_size.auto_scale()}\")\n```\n\n## Supported Units\n\n### Binary Units (Base 1024)\n- `BYTES` (1 byte)\n- `KIB` (1,024 bytes)\n- `MIB` (1,048,576 bytes)\n- `GIB`, `TIB`, `PIB`, `EIB`, `ZIB`, `YIB`\n\n### Decimal Units (Base 1000)\n- `KB` (1,000 bytes)\n- `MB` (1,000,000 bytes)\n- `GB` (1,000,000,000 bytes)\n- `TB`, `PB`, `EB`, `ZB`, `YB`\n\n### Bit Units\n- `BITS` (1/8 byte)\n- `KILOBITS`, `MEGABITS`, `GIGABITS`, `TERABITS`, `PETABITS`, `EXABITS`, `ZETTABITS`, `YOTTABITS`\n\n## Advanced Usage\n\n### Platform-Specific Optimizations\n\n```python\nfrom byteunit import Storage\n\n# Automatically detect and use platform-specific optimizations\nplatform_storage = Storage.get_platform_storage()\nsize = platform_storage.get_size_from_path(\"/large/directory\")\n\n# Platform info\ninfo = platform_storage.get_platform_info()\nprint(f\"Platform: {info['platform']}\")\nprint(f\"Optimizations: {info.get('api_optimization', 'none')}\")\n```\n\n### String Parsing Features\n\nThe `parse()` method supports various input formats:\n\n```python\nfrom byteunit import Storage, StorageUnit\n\n# Case insensitive\nStorage.parse(\"1.5 mb\") # Works\nStorage.parse(\"1.5 MB\") # Works\nStorage.parse(\"1.5 Mb\") # Works\n\n# Decimal separators\nStorage.parse(\"1.5 MB\") # Dot separator\nStorage.parse(\"1,5 MB\") # Comma separator\n\n# Spacing\nStorage.parse(\"1.5 MB\") # With space\nStorage.parse(\"1.5MB\") # Without space\n\n# Default unit\nStorage.parse(\"1024\") # Defaults to bytes\nStorage.parse(\"1024\", StorageUnit.KIB) # Custom default\n\n# Comprehensive unit aliases\nStorage.parse(\"1 kilobyte\") # Full name\nStorage.parse(\"1 kb\") # Abbreviation\nStorage.parse(\"1 k\") # Single letter\n```\n\n### Error Handling\n\n```python\nfrom byteunit import Storage, StorageUnit\n\n# Invalid values raise appropriate exceptions\ntry:\n Storage(-1, StorageUnit.BYTES) # Raises ValueError\nexcept ValueError as e:\n print(f\"Error: {e}\")\n\ntry:\n Storage.parse(\"invalid\") # Raises ValueError\nexcept ValueError as e:\n print(f\"Parsing error: {e}\")\n\ntry:\n storage = Storage(1, StorageUnit.KIB)\n result = storage / 0 # Raises ZeroDivisionError\nexcept ZeroDivisionError as e:\n print(f\"Division error: {e}\")\n```\n\n## Real-World Examples\n\n### Download Time Calculator\n\nByteUnit is the same thing as Storage, so you can use either interchangeably.\n\n```python\nfrom byteunit import ByteUnit\n\n# File sizes\nmovie = ByteUnit.parse(\"1.4 GB\")\nsong = ByteUnit.parse(\"4.5 MB\")\n\n# Network speeds (in bits per second)\nbroadband = ByteUnit.parse(\"50 Megabits\") # 50 Mbps\nfiber = ByteUnit.parse(\"1 Gigabit\") # 1 Gbps\n\n# Calculate download times\nmovie_time_broadband = movie / broadband # seconds\nmovie_time_fiber = movie / fiber # seconds\n\nprint(f\"Movie download time:\")\nprint(f\" Broadband (50 Mbps): {movie_time_broadband:.1f} seconds\")\nprint(f\" Fiber (1 Gbps): {movie_time_fiber:.1f} seconds\")\n```\n\n### Storage Capacity Planning\n\n```python\nfrom byteunit import ByteUnit\n\n# Calculate total storage needs\nphotos = ByteUnit.parse(\"2.8 MiB\") * 2000 # 2000 photos\nmusic = ByteUnit.parse(\"4.5 MB\") * 500 # 500 songs\nvideos = ByteUnit.parse(\"1.2 GB\") * 50 # 50 videos\ndocuments = ByteUnit.parse(\"250 KB\") * 1000 # 1000 documents\n\ntotal_needed = photos + music + videos + documents\nprint(f\"Total storage needed: {total_needed.auto_scale()}\")\n\n# Available storage\navailable = ByteUnit.parse(\"500 GB\")\nremaining = available - total_needed\nprint(f\"Remaining space: {remaining.auto_scale()}\")\n```\n\n## Development\n\n### Running Tests\n\n```bash\n# Run basic functionality tests\npython test_basic_functionality.py\n```\n\n### Building and Installation\n\nplease install uv first\n\n```bash\n# Install development dependencies\nuv sync\n```\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.",
"bugtrack_url": null,
"license": "MIT",
"summary": "A unified storage unit library for Python with cross-platform file size support",
"version": "0.6.4",
"project_urls": {
"Changelog": "https://github.com/byteunit-dev/byteunit/blob/main/CHANGELOG.md",
"Documentation": "https://byteunit.readthedocs.io",
"Homepage": "https://github.com/byteunit-dev/byteunit",
"Issues": "https://github.com/byteunit-dev/byteunit/issues",
"Repository": "https://github.com/byteunit-dev/byteunit.git"
},
"split_keywords": [
"bytes",
" conversion",
" cross-platform",
" file-size",
" pathlib",
" storage",
" units"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "4535429873e38cbec1da7ae195fa8bc5cb888f10572c3329d93894fe2c7ea96a",
"md5": "e96494eae490ce925969e42e23883760",
"sha256": "63b4a4b74d35e944cc6b1df192c6c75755766e6ad33a28e5d65a0ce8c7e5c406"
},
"downloads": -1,
"filename": "filesizelib-0.6.4-py3-none-any.whl",
"has_sig": false,
"md5_digest": "e96494eae490ce925969e42e23883760",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.9",
"size": 17825,
"upload_time": "2025-07-22T10:47:37",
"upload_time_iso_8601": "2025-07-22T10:47:37.378826Z",
"url": "https://files.pythonhosted.org/packages/45/35/429873e38cbec1da7ae195fa8bc5cb888f10572c3329d93894fe2c7ea96a/filesizelib-0.6.4-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "57be86cc53a315f2486945772f747e5965219a95a6bc548861f877973ca7e8a0",
"md5": "a663a80bbef1825cc070e285ac801ddc",
"sha256": "2b31045484f3c1ee0a5a197c3a3a92c5adee339d177000aceae77dbf9b2e4551"
},
"downloads": -1,
"filename": "filesizelib-0.6.4.tar.gz",
"has_sig": false,
"md5_digest": "a663a80bbef1825cc070e285ac801ddc",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9",
"size": 112450,
"upload_time": "2025-07-22T10:47:39",
"upload_time_iso_8601": "2025-07-22T10:47:39.560772Z",
"url": "https://files.pythonhosted.org/packages/57/be/86cc53a315f2486945772f747e5965219a95a6bc548861f877973ca7e8a0/filesizelib-0.6.4.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-07-22 10:47:39",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "byteunit-dev",
"github_project": "byteunit",
"github_not_found": true,
"lcname": "filesizelib"
}