str-or-none
A tiny Python utility to safely convert a value to a str or None.
- Returns a stripped string if possible, or
Noneif the value isNone. - Raises
ValueErrorfor non-string types in strict mode (default). - Supports file-like objects, numbers, datetimes, sequences, dicts, and custom objects.
- Can be used as a function or directly as a module call.
Usage
import str_or_none
# or: from str_or_none import str_or_none
str_or_none(" hello ") # 'hello'
str_or_none(None) # None
str_or_none(123) # ValueError (strict mode)
str_or_none(123, strict=False) # '123'
str_or_none([1, 2, 3], strict=False) # '[1, 2, 3]'
str_or_none({"a": 1}, strict=False) # '{"a": 1}'
import io
str_or_none(io.StringIO(" hi ")) # 'hi'
str_or_none(" hi ", strip=False) # ' hi '
class Custom:
def __str__(self):
return "custom!"
str_or_none(Custom(), strict=False) # 'custom!'
str_or_none("") # None (default: empty_str_to_none=True)
str_or_none("", empty_str_to_none=False) # ''
str_or_none(" ") # None (after strip)
str_or_none(" ", empty_str_to_none=False) # ''
API
def str_or_none(value, *, strip=True, strict=True, empty_str_to_none=True) -> Optional[str]:
...
strip: Remove leading/trailing whitespace (default: True)strict: RaiseValueErrorfor non-string types (default: True)empty_str_to_none: If True, return None for empty strings (after optional strip). Default: True.
Returns a string or None, or raises ValueError if conversion is not allowed.
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
str_or_none-0.1.0.tar.gz
(2.8 kB
view details)
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file str_or_none-0.1.0.tar.gz.
File metadata
- Download URL: str_or_none-0.1.0.tar.gz
- Upload date:
- Size: 2.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via:
poetry/1.8.5 CPython/3.8.20 Darwin/24.4.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ccced5fe5eb8d953fa1f1a708416366afe5a0e2682c3112c1843766a4633e808
|
|
| MD5 |
0ca0d15bbca1a19bea28a4c8c138e800
|
|
| BLAKE2b-256 |
6ad1ccd34835b091493ad6a763f45026734d6a144980eae4a482b4b5926d5036
|
File details
Details for the file str_or_none-0.1.0-py3-none-any.whl.
File metadata
- Download URL: str_or_none-0.1.0-py3-none-any.whl
- Upload date:
- Size: 3.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via:
poetry/1.8.5 CPython/3.8.20 Darwin/24.4.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2ee71ce3bffd169af56e5b85ba841f6af71d27bc4c93e49c51cbfe68f608caaf
|
|
| MD5 |
a2f27f09e71be77bf796f47bbb213648
|
|
| BLAKE2b-256 |
947511de071666160778f9822f1b921902a3f00773b7f32f38673748957140ad
|