String Module API Reference¶
normalize(x: Union[str, AutoEnum], *, remove: Optional[Union[str, Tuple, List, Set]] = (' ', '-', '_')) -> str
¶
Normalize a string by removing specified characters and converting to lowercase.
This function is optimized for performance and found to be faster than .translate() and re.sub() on Python 3.10.6+. Useful for creating canonical identifiers, comparing strings in a case-insensitive way, or cleaning up user input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Union[str, AutoEnum]
|
The string or AutoEnum to normalize. |
required |
remove
|
Optional[Union[str, Tuple, List, Set]]
|
Characters to remove from the string. Can be: - str: Single character or string of characters to remove - Tuple/List/Set: Collection of characters to remove - None: No characters removed (only lowercase) Defaults to (" ", "-", "_"). |
(' ', '-', '_')
|
Returns:
| Type | Description |
|---|---|
str
|
Normalized string with specified characters removed and converted to lowercase. |
Examples:
# Basic usage
assert normalize("Hello World") == "helloworld"
assert normalize("snake_case") == "snakecase"
assert normalize("kebab-case") == "kebabcase"
# Custom removal characters
assert normalize("foo@bar.com", remove=("@", ".")) == "foobarcom"
# No removal, just lowercase
assert normalize("CamelCase", remove=None) == "camelcase"
# With AutoEnum
from morphic import AutoEnum
class Color(AutoEnum):
DARK_BLUE = ()
assert normalize(Color.DARK_BLUE) == "darkblue"
Note
This function only removes characters, it does not replace them. Use convert_case() if you need to convert between different naming conventions.
Source code in src/morphic/string.py
punct_normalize(x: str, *, lowercase: bool = True, space: bool = True, numbers: bool = False) -> str
¶
Normalize a string by removing punctuation and optionally spaces/numbers.
This function uses precomputed translation tables for maximum performance. Useful for text processing, search normalization, and creating clean identifiers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
str
|
The string to normalize. |
required |
lowercase
|
bool
|
If True, convert to lowercase. Defaults to True. |
True
|
space
|
bool
|
If True, remove spaces. Defaults to True. |
True
|
numbers
|
bool
|
If True, remove numbers (0-9). Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
str
|
Normalized string with punctuation removed and optional transformations applied. |
Examples:
# Basic usage - removes punctuation, spaces, and lowercases
assert punct_normalize("Hello, World!") == "helloworld"
# Keep spaces
assert punct_normalize("Hello, World!", space=False) == "hello world"
# Keep case
assert punct_normalize("Hello, World!", lowercase=False) == "HelloWorld"
# Remove numbers too
assert punct_normalize("abc123def", numbers=True) == "abcdef"
# Keep everything except punctuation
assert punct_normalize("Test-123: Done!", lowercase=False, space=False) == "Test123 Done"
Note
Punctuation is defined by Python's string.punctuation constant: !"#$%&'()*+,-./:;<=>?@[]^_`{|}~
Source code in src/morphic/string.py
whitespace_normalize(text: str, remove_newlines: bool = False) -> str
¶
Normalize whitespace in a string by removing extra spaces and newlines.
This function performs several whitespace cleanup operations: - Removes trailing whitespace at the end of each line - Collapses multiple consecutive newlines into single newlines (or removes them) - Collapses multiple consecutive spaces into single spaces - Strips leading/trailing whitespace from the entire string
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The string to normalize. |
required |
remove_newlines
|
bool
|
If True, removes all newlines. If False, collapses multiple newlines into single newlines. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
str
|
Normalized string with cleaned up whitespace. |
Examples:
# Basic usage - collapses whitespace
assert whitespace_normalize("hello world") == "hello world"
assert whitespace_normalize("line1\n\n\nline2") == "line1\nline2"
# Remove newlines entirely
assert whitespace_normalize("line1\nline2", remove_newlines=True) == "line1 line2"
# Clean up messy text
messy = " hello world \n\n foo bar \n\n "
clean = whitespace_normalize(messy)
assert clean == "hello world\nfoo bar"
# Trailing whitespace removed from each line
text = "line1 \nline2 \nline3"
assert whitespace_normalize(text) == "line1\nline2\nline3"
Note
This function is useful for cleaning up text from various sources (user input, scraped HTML, log files) before further processing.
Source code in src/morphic/string.py
hash(val: Union[str, int, float, List, Dict], *, base: int = 62) -> str
¶
Constructs a hash of a JSON object or value. :param val: any valid JSON value (including str, int, float, list, and dict). :param base: the base of the output hash. Defaults to base56, which encodes the output in a ASCII-chars :return: SHA256 hash.
Source code in src/morphic/string.py
format_exception_msg(ex: Exception, short: bool = False, prefix: Optional[str] = None) -> str
¶
Format exception messages with optional traceback information.
Provides a utility for formatting exception messages with configurable detail levels and optional prefixes. Used internally by Typed for enhanced error reporting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ex
|
Exception
|
The exception to format. |
required |
short
|
bool
|
Whether to use short format for traceback. Defaults to False (full traceback). |
False
|
prefix
|
Optional[str]
|
Optional prefix to add to the message. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Formatted exception message with traceback information. |
Examples:
try:
raise ValueError("Something went wrong")
except Exception as e:
# Short format
short_msg = format_exception_msg(e, short=True)
print(short_msg)
# "ValueError: 'Something went wrong'\nTrace: file.py#123; "
# Full format with prefix
full_msg = format_exception_msg(e, prefix="Validation Error")
print(full_msg)
# "Validation Error: ValueError: 'Something went wrong'\nTraceback:\n\tfile.py line 123, in function..."
Note
This is primarily an internal utility function used by Typed's error handling. Reference: https://stackoverflow.com/a/64212552
Source code in src/morphic/string.py
str_format_args(x: str, *, named_only: bool = True) -> List[str]
¶
Extract format argument names from a format string.
Parses a Python format string and returns the list of argument names/indices used in the string. Useful for validating format strings, introspection, and dynamic template processing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
str
|
A Python format string (e.g., "Hello {name}, you are {age} years old"). |
required |
named_only
|
bool
|
If True, only return named arguments (not positional indices). Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
List[str]
|
List of argument names/indices found in the format string. |
Examples:
# Named arguments
assert str_format_args("Hello {name}!") == ["name"]
assert str_format_args("{first} {last}") == ["first", "last"]
# Positional arguments (with named_only=False)
assert str_format_args("Hello {0}!", named_only=False) == ["0"]
assert str_format_args("{0} {1}", named_only=False) == ["0", "1"]
# Mixed arguments
assert str_format_args("{0} {name} {1}", named_only=False) == ["0", "name", "1"]
assert str_format_args("{0} {name} {1}", named_only=True) == ["name"]
# No arguments
assert str_format_args("No arguments here") == []
# Duplicate arguments
assert str_format_args("{x} and {x}") == ["x", "x"]
Note
Reference: https://stackoverflow.com/a/46161774/4900327
Source code in src/morphic/string.py
is_not_empty_bytes(string: bytes) -> bool
¶
Check if a bytes object is not empty (contains non-whitespace content).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
string
|
bytes
|
The bytes object to check. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the bytes object contains non-whitespace content, False otherwise. |
Examples:
assert is_not_empty_bytes(b"hello") is True
assert is_not_empty_bytes(b" content ") is True
assert is_not_empty_bytes(b"") is False
assert is_not_empty_bytes(b" ") is False
Source code in src/morphic/string.py
is_empty(string: Any) -> bool
¶
Check if a string is empty or contains only whitespace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
string
|
Any
|
The value to check (typically a string). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the string is empty or contains only whitespace, False otherwise. |
Examples:
assert is_empty("") is True
assert is_empty(" ") is True
assert is_empty("hello") is False
assert is_empty(" hello ") is False
assert is_empty(123) is True # Non-strings are considered empty
Note
This is the inverse of _is_not_empty(). Non-string types are considered empty.
Source code in src/morphic/string.py
is_int(string: Any) -> bool
¶
Check if a value can be parsed as an integer.
Tests whether the input can be successfully converted to an integer using int(). This function does NOT accept float strings like '123.0' as integers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
string
|
Any
|
The value to check (typically a string). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the value can be parsed as an integer, False otherwise. |
Examples:
# Valid integers
assert is_int("123") is True
assert is_int("-123") is True
assert is_int("0") is True
# Not integers
assert is_int("123.0") is False # Has decimal point
assert is_int("1.23") is False
assert is_int("-1.23") is False
assert is_int("1e2") is False # Scientific notation
assert is_int("abc") is False
assert is_int("") is False
Note
This function accepts any type as input but returns True only for values that can be parsed as integers. It does not raise exceptions.
Source code in src/morphic/string.py
is_float(string: Any) -> bool
¶
Check if a value can be parsed as a floating-point number.
Tests whether the input can be successfully converted to a float using float(). This function accepts integers, decimals, scientific notation, and special values like NaN and infinity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
string
|
Any
|
The value to check (typically a string). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the value can be parsed as a float, False otherwise. |
Examples:
# Valid floats
assert is_float("123") is True
assert is_float("1.23") is True
assert is_float("123.0") is True
assert is_float("-123") is True
assert is_float("-123.0") is True
assert is_float("1e2") is True
assert is_float("1.23e-5") is True
assert is_float("nan") is True
assert is_float("NAN") is True
assert is_float("inf") is True
assert is_float("-inf") is True
# Not floats
assert is_float("abc") is False
assert is_float("") is False
assert is_float("12.34.56") is False
Note
This function returns True for special float values like NaN and infinity. It accepts any type as input but returns True only for values that can be parsed as floats. It does not raise exceptions.
Source code in src/morphic/string.py
join_human(l: Union[List, Tuple, Set], sep: str = ',', final_join: str = 'and', oxford_comma: bool = False) -> str
¶
Join a list of items into a human-readable string with proper grammar.
Creates grammatically correct conjunctions for lists of items, with support for Oxford comma style. Useful for generating user-facing messages, error messages, and natural language output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
l
|
Union[List, Tuple, Set]
|
A list, tuple, or set of items to join. |
required |
sep
|
str
|
Separator between items (except the last). Defaults to ",". |
','
|
final_join
|
str
|
Word to use before the last item. Defaults to "and". |
'and'
|
oxford_comma
|
bool
|
If True, uses Oxford comma style (includes separator before final_join). Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
str
|
A human-readable string with proper grammar. |
Examples:
# Basic usage
assert join_human(["apple", "banana", "cherry"]) == "apple, banana and cherry"
# With Oxford comma
assert join_human(["apple", "banana", "cherry"], oxford_comma=True) == "apple, banana, and cherry"
# Two items
assert join_human(["Alice", "Bob"]) == "Alice and Bob"
# Single item
assert join_human(["Alice"]) == "Alice"
# Custom separator and conjunction
assert join_human([1, 2, 3], sep=";", final_join="or") == "1; 2 or 3"
# With tuple or set
assert join_human(("red", "green", "blue")) == "red, green and blue"
assert "alpha" in join_human({"alpha", "beta", "gamma"})
Note
Empty lists/sets will return an empty string after stripping.
Source code in src/morphic/string.py
convert_str_to_type(val: str, expected_type: Type) -> Any
¶
Convert a string representation to a specific Python type.
Parses string literals and converts them to the expected Python type. Handles automatic type coercion between compatible types (e.g., int to float, list to tuple). Useful for parsing configuration files, command-line arguments, and user input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
val
|
str
|
String representation of the value to convert. |
required |
expected_type
|
Type
|
The target Python type (e.g., int, float, bool, list, dict, etc.). |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The converted value of the expected type. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the string cannot be converted to the expected type. |
TypeError
|
If expected_type is not a type object. |
SyntaxError
|
If the string is not valid Python literal syntax. |
Examples:
# Basic types
assert convert_str_to_type("123", int) == 123
assert convert_str_to_type("12.5", float) == 12.5
assert convert_str_to_type("true", bool) is True
assert convert_str_to_type("False", bool) is False
# Collections
assert convert_str_to_type("[1, 2, 3]", list) == [1, 2, 3]
assert convert_str_to_type("(1, 2, 3)", tuple) == (1, 2, 3)
assert convert_str_to_type("{1, 2, 3}", set) == {1, 2, 3}
assert convert_str_to_type("{'a': 1}", dict) == {'a': 1}
# Type coercion
assert convert_str_to_type("5", float) == 5.0 # int to float
assert convert_str_to_type("5.0", int) == 5 # float to int (if whole number)
assert convert_str_to_type("[1, 2]", tuple) == (1, 2) # list to tuple
assert convert_str_to_type("(1, 2)", list) == [1, 2] # tuple to list
# Already correct type
assert convert_str_to_type("hello", str) == "hello"
Note
This function uses ast.literal_eval() for safety, so only Python literal structures are supported (strings, numbers, tuples, lists, dicts, booleans, None). Arbitrary Python expressions are not evaluated.
Source code in src/morphic/string.py
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 | |
readable_bytes(size_in_bytes: int, decimals: int = 3) -> str
¶
Convert bytes to a human-readable string with appropriate units.
Automatically selects the most appropriate unit (B, KB, MB, GB, etc.) based on the size, choosing the largest unit where the value is >= 1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size_in_bytes
|
int
|
The size in bytes to format. |
required |
decimals
|
int
|
Number of decimal places to round to. Defaults to 3. |
3
|
Returns:
| Type | Description |
|---|---|
str
|
A formatted string with the size and unit (e.g., "5.2 MB", "1.5 GB"). |
Examples:
assert "500" in readable_bytes(500) and "B" in readable_bytes(500)
assert "KB" in readable_bytes(5000)
assert "MB" in readable_bytes(5000000)
assert "GB" in readable_bytes(5000000000)
# With custom decimals
result = readable_bytes(1500, decimals=1)
assert "1.5 KB" in result or "1.465 KB" in result
See Also
convert_size_from_bytes() for more control over unit selection.
Source code in src/morphic/string.py
convert_size_from_bytes(size_in_bytes: int, unit: Optional[str] = None, decimals: int = 3) -> Union[Dict, float]
¶
Convert bytes to various size units.
Converts a byte count to all standard size units (B, KB, MB, GB, TB, PB, EB, ZB, YB). Can return all conversions or a specific unit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size_in_bytes
|
int
|
The size in bytes to convert. |
required |
unit
|
Optional[str]
|
If specified, returns only this unit. Must be one of FILE_SIZE_UNITS. If None, returns a dict with all units. Defaults to None. |
None
|
decimals
|
int
|
Number of decimal places to round to. Defaults to 3. |
3
|
Returns:
| Type | Description |
|---|---|
Union[Dict, float]
|
If unit is None: Dict mapping unit names to converted values. |
Union[Dict, float]
|
If unit is specified: Float value in that unit. |
Examples:
# Get all conversions
sizes = convert_size_from_bytes(1024)
assert sizes["B"] == 1024.0
assert sizes["KB"] == 1.0
# Get specific unit
kb_size = convert_size_from_bytes(2048, unit="KB")
assert kb_size == 2.0
# Larger sizes
sizes = convert_size_from_bytes(1024 * 1024 * 1024) # 1 GB
assert sizes["GB"] == 1.0
Note
Conversion uses 1024-based units (binary), not 1000-based (decimal).
Source code in src/morphic/string.py
convert_size_to_bytes(size_in_human_readable: str) -> int
¶
Parse a human-readable size string and convert to bytes.
Accepts strings like "1 KB", "5.5 MB", "2GB" and converts them to bytes. Case-insensitive and spaces are optional.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size_in_human_readable
|
str
|
Size string with value and unit (e.g., "5 MB", "1.5GB"). |
required |
Returns:
| Type | Description |
|---|---|
int
|
Size in bytes as an integer. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the string format is invalid or unit is unrecognized. |
Examples:
assert convert_size_to_bytes("1 KB") == 1024
assert convert_size_to_bytes("1 MB") == 1024 * 1024
assert convert_size_to_bytes("1.5 KB") == int(1.5 * 1024)
# Case insensitive
assert convert_size_to_bytes("5 kb") == 5 * 1024
assert convert_size_to_bytes("5KB") == 5 * 1024
# Various formats
assert convert_size_to_bytes("2 GB") == 2 * 1024 * 1024 * 1024
assert convert_size_to_bytes("500 B") == 500
Note
Uses 1024-based units (binary), not 1000-based (decimal).
Source code in src/morphic/string.py
readable_seconds(time_in_seconds: Union[float, timedelta], *, decimals: int = 2, short: bool = False) -> str
¶
Convert seconds to a human-readable time string with appropriate units.
Automatically selects the most appropriate time unit (ns, us, ms, s, min, hr, d) based on the duration, choosing the largest unit where the value is >= 1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time_in_seconds
|
Union[float, timedelta]
|
Time duration in seconds, or a timedelta object. |
required |
decimals
|
int
|
Number of decimal places to round to. Defaults to 2. |
2
|
short
|
bool
|
If True, uses short unit names (e.g., "s", "min", "hr"). If False, uses long unit names (e.g., "seconds", "mins", "hours"). Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
str
|
A formatted string with the time and unit (e.g., "5.2 seconds", "3 mins", "1.5 hr"). |
Examples:
assert "5" in readable_seconds(5) and "s" in readable_seconds(5)
assert "min" in readable_seconds(120, short=True) or "mins" in readable_seconds(120)
assert "hr" in readable_seconds(7200, short=True) or "hours" in readable_seconds(7200)
# With timedelta
from datetime import timedelta
td = timedelta(seconds=30)
result = readable_seconds(td)
assert "30" in result
# Short format
assert readable_seconds(5, short=True) in ["5.0s", "5s"]
See Also
convert_time_from_seconds() for more control over unit selection.
Source code in src/morphic/string.py
convert_time_from_seconds(time_in_seconds: float, unit: Optional[str] = None, decimals: int = 3, short: bool = False) -> Union[Dict, float]
¶
Convert seconds to various time units.
Converts a duration in seconds to all standard time units (nanoseconds, microseconds, milliseconds, seconds, mins, hours, days). Can return all conversions or a specific unit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time_in_seconds
|
float
|
The duration in seconds to convert. |
required |
unit
|
Optional[str]
|
If specified, returns only this unit (e.g., "mins", "hours"). If None, returns a dict with all units. Defaults to None. |
None
|
decimals
|
int
|
Number of decimal places to round to. Defaults to 3. |
3
|
short
|
bool
|
If True, uses short unit names in the returned dict keys (e.g., "s", "min", "hr"). If False, uses long names (e.g., "seconds", "mins", "hours"). Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Union[Dict, float]
|
If unit is None: Dict mapping unit names to converted values. |
Union[Dict, float]
|
If unit is specified: Float value in that unit. |
Examples:
# Get all conversions
times = convert_time_from_seconds(60)
assert times["seconds"] == 60.0
assert times["mins"] == 1.0
# Get specific unit
mins = convert_time_from_seconds(120, unit="mins")
assert mins == 2.0
# Short format
times = convert_time_from_seconds(5, short=True)
assert "s" in times
assert "ms" in times
assert times["s"] == 5.0
assert times["ms"] == 5000.0
Note
Unit names are case-insensitive when requesting a specific unit.
Source code in src/morphic/string.py
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 | |
readable_number(n: Union[float, int], decimals: int = 3, short: bool = True, scientific: bool = False) -> str
¶
Convert a number to a human-readable string with appropriate unit suffix.
Automatically formats large numbers with unit suffixes (K, M, B, T, etc.) or uses scientific notation for small numbers. Useful for displaying statistics, counts, and metrics in a compact, readable format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
Union[float, int]
|
The number to format (positive or negative). |
required |
decimals
|
int
|
Number of decimal places to round to. Defaults to 3. |
3
|
short
|
bool
|
If True, uses short unit names (e.g., "K", "M", "B"). If False, uses long unit names (e.g., "thousand", "million", "billion"). Defaults to True. |
True
|
scientific
|
bool
|
If True, forces scientific notation. If False, automatically uses scientific notation for numbers with 0 < abs(n) < 1. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
str
|
A formatted string with the number and unit suffix (e.g., "1K", "5.2M", "3B"). |
Examples:
# Large numbers with short units
assert readable_number(1000, short=True) == "1K"
assert readable_number(1000000, short=True) == "1M"
assert readable_number(1000000000, short=True) == "1B"
# Long format
assert readable_number(1000, short=False) == "1 thousand"
assert readable_number(1000000, short=False) == "1 million"
# Small numbers use scientific notation
result = readable_number(0.00123)
assert "e" in result
# Zero
assert readable_number(0) == "0"
# Negative numbers
result = readable_number(-1500, short=True)
assert "-" in result and ("1.5K" in result or "1500" in result)
See Also
convert_number() for more control over unit selection.
Source code in src/morphic/string.py
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 | |
convert_number(n: float, unit: Optional[str] = None, decimals: int = 3, short: bool = False) -> Union[Dict, float]
¶
Convert a number to various magnitude units.
Converts a number to units like thousand, million, billion, etc. (or their short forms K, M, B). Can return all conversions or a specific unit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
float
|
The number to convert. Must be non-negative. |
required |
unit
|
Optional[str]
|
If specified, returns only this unit (e.g., "K", "million"). If None, returns a dict with all units. Defaults to None. |
None
|
decimals
|
int
|
Number of decimal places to round to. Defaults to 3. |
3
|
short
|
bool
|
If True, uses short unit names in the returned dict keys (e.g., "K", "M", "B"). If False, uses long names (e.g., "thousand", "million", "billion"). Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Union[Dict, float]
|
If unit is None: Dict mapping unit names to converted values. |
Union[Dict, float]
|
If unit is specified: Float value in that unit. |
Examples:
# Get all conversions
numbers = convert_number(1000000, short=True)
assert numbers["M"] == 1.0
assert numbers["K"] == 1000.0
# Get specific unit
millions = convert_number(5000000, unit="M", short=True)
assert millions == 5.0
# Long format
numbers = convert_number(1000, short=False)
assert "thousand" in numbers
assert numbers["thousand"] == 1.0
# Base unit (no suffix)
numbers = convert_number(500, short=True)
assert numbers[""] == 500.0 # Base unit has empty string key
Raises:
| Type | Description |
|---|---|
AssertionError
|
If n is negative. |
Note
The function requires n >= 0. Use abs(n) if you need to handle negative numbers.
Source code in src/morphic/string.py
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 | |
detect_case(s: str) -> Literal['snake', 'screaming_snake', 'kebab', 'train', 'camel', 'pascal', 'studly']
¶
Detects the case of the input literal name.
Returns:
| Type | Description |
|---|---|
Literal['snake', 'screaming_snake', 'kebab', 'train', 'camel', 'pascal', 'studly']
|
One of: - 'snake' for snake_case, - 'screaming_snake' for SCREAMING_SNAKE_CASE, - 'kebab' for kebab-case, - 'train' for TRAIN-CASE, - 'camel' for camelCase, - 'pascal' for PascalCase. - 'studly' for StUDlyCaSe |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input string is empty, contains unsupported characters, or uses mixed delimiters. |
Source code in src/morphic/string.py
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 | |
convert_case(s: str, target_case: Literal['upper', 'lower', 'snake', 'screaming_snake', 'kebab', 'train', 'camel', 'pascal', 'studly']) -> list
¶
Convert a string from one case format to another.
This function detects the source case format automatically and converts the string to the specified target case format.
Supported case formats
- 'snake': snake_case (words separated by underscores, all lowercase)
- 'screaming_snake': SCREAMING_SNAKE_CASE (words separated by underscores, all uppercase)
- 'kebab': kebab-case (words separated by hyphens, all lowercase)
- 'train': TRAIN-CASE (words separated by hyphens, all uppercase)
- 'camel': camelCase (no separators, first word lowercase, subsequent words capitalized)
- 'pascal': PascalCase (no separators, all words capitalized)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
s
|
str
|
The input string to convert |
required |
target_case
|
Literal['upper', 'lower', 'snake', 'screaming_snake', 'kebab', 'train', 'camel', 'pascal', 'studly']
|
The target case format to convert to |
required |
Returns:
| Type | Description |
|---|---|
list
|
The converted string in the target case format |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the source case cannot be detected or if the target case is unsupported |
Examples:
>>> assert convert_case("CachedResultsStep", "kebab") == "cached-results-step"
>>> assert convert_case("cachedResultsStep", "snake") == "cached_results_step"
>>> assert convert_case("cached_results_step", "pascal") == "CachedResultsStep"
>>> assert convert_case("cached-results-step", "camel") == "cachedResultsStep"
>>> assert convert_case("CACHED_RESULTS_STEP", "camel") == "cachedResultsStep"
>>> assert convert_case("Test123Case", "snake") == "test_123_case"
>>> assert convert_case("another_test_case", "kebab") == "another-test-case"
Source code in src/morphic/string.py
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 | |
get_num_zeros_to_pad(max_i: int) -> int
¶
Calculate the number of digits needed to pad numbers up to max_i.
Determines how many digits are required to represent the largest number in a sequence, useful for creating zero-padded filenames, IDs, or indices that sort correctly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_i
|
int
|
The maximum integer value that needs to be represented. Must be >= 1. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of digits needed for zero-padding. |
Examples:
# For numbers 1-99
assert get_num_zeros_to_pad(99) == 2
# For numbers 1-100
assert get_num_zeros_to_pad(100) == 3
# For numbers 1-999
assert get_num_zeros_to_pad(999) == 3
# For numbers 1-1000
assert get_num_zeros_to_pad(1000) == 4
# Single digit
assert get_num_zeros_to_pad(9) == 1
assert get_num_zeros_to_pad(10) == 2
Note
Reference: https://stackoverflow.com/a/51837162/4900327
Source code in src/morphic/string.py
zfill(i: int, max_i: int = int(1000000000000.0)) -> str
¶
Zero-pad an integer based on the maximum value in the sequence.
Creates a zero-padded string representation of an integer, with padding length determined by the maximum value. Ensures all numbers in a sequence have the same width, which is important for lexicographic sorting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
i
|
int
|
The integer to zero-pad. Must be >= 0. |
required |
max_i
|
int
|
The maximum integer in the sequence. Must be >= i. Defaults to 1 trillion (1e12). |
int(1000000000000.0)
|
Returns:
| Type | Description |
|---|---|
str
|
Zero-padded string representation of the integer. |
Examples:
# Basic usage - padding for numbers up to 999
assert zfill(5, 999) == "005"
assert zfill(42, 999) == "042"
assert zfill(999, 999) == "999"
# Padding for numbers up to 100
assert zfill(1, 100) == "001"
assert zfill(99, 100) == "099"
assert zfill(100, 100) == "100"
# Creating sorted filenames
for i in range(10):
filename = f"file_{zfill(i, 100)}.txt"
# Results in: file_000.txt, file_001.txt, ..., file_009.txt
# With default max (1 trillion)
assert len(zfill(1)) == 13 # Padded to 13 digits
Raises:
| Type | Description |
|---|---|
TypeError
|
If i or max_i are not integers. |
ValueError
|
If i < 0 or max_i < i. |
Note
This is particularly useful for creating filenames that sort correctly in file explorers and when globbing files.
Source code in src/morphic/string.py
random_name(count: int = 1, *, sep: str = HYPHEN, order: Tuple[str, ...] = ('adjective', 'verb', 'noun'), seed: Optional[int] = None) -> Union[List[str], str]
¶
Generate random human-readable names from word combinations.
Creates memorable random names by combining adjectives, verbs, and nouns (e.g., "quick-running-fox", "happy-jumping-dog"). Useful for generating unique identifiers, test data, project names, or placeholder names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
count
|
int
|
Number of random names to generate. Defaults to 1. |
1
|
sep
|
str
|
Separator between words. Defaults to "-" (hyphen). |
HYPHEN
|
order
|
Tuple[str, ...]
|
Tuple specifying the order and types of words to combine. Each element must be "adjective", "verb", or "noun". Defaults to ("adjective", "verb", "noun"). |
('adjective', 'verb', 'noun')
|
seed
|
Optional[int]
|
Random seed for reproducible results. Defaults to None (random). |
None
|
Returns:
| Type | Description |
|---|---|
Union[List[str], str]
|
If count == 1, returns a single string. |
Union[List[str], str]
|
If count > 1, returns a list of strings. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If order contains an unrecognized word type. |
ValueError
|
If count exceeds the number of possible combinations. |
TypeError
|
If parameters have incorrect types. |
Examples:
# Generate single name
name = random_name() # e.g., "happy-running-dog"
# Generate multiple names
names = random_name(3) # e.g., ["quick-jumping-fox", "lazy-sleeping-cat", ...]
# Custom separator
name = random_name(sep="_") # e.g., "brave_flying_eagle"
# Custom order
name = random_name(order=("adjective", "noun")) # e.g., "blue-sky"
name = random_name(order=("verb", "noun")) # e.g., "running-tiger"
# Reproducible with seed
name1 = random_name(seed=42)
name2 = random_name(seed=42)
assert name1 == name2
# Multiple with seed
names = random_name(5, seed=123) # Always generates same 5 names
Note
The function ensures all generated names in a batch are unique. Maximum possible combinations depends on the word lists and order.
Source code in src/morphic/string.py
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 | |
parse_datetime(dt: Union[str, int, float, datetime]) -> datetime
¶
Parse various datetime representations into a datetime object.
Accepts multiple input formats and normalizes them to Python datetime objects. Useful for handling datetime inputs from various sources (APIs, databases, user input).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
Union[str, int, float, datetime]
|
The datetime to parse. Can be: - datetime object (returned as-is) - int/float (interpreted as Unix timestamp) - str (parsed as ISO format string) |
required |
Returns:
| Type | Description |
|---|---|
datetime
|
A datetime object. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the input type is not supported. |
ValueError
|
If the string format is invalid. |
Examples:
from datetime import datetime
# datetime object (pass-through)
dt = datetime.now()
assert parse_datetime(dt) == dt
# Unix timestamp (int)
assert parse_datetime(1609459200).year == 2021
# Unix timestamp (float with microseconds)
assert parse_datetime(1609459200.5).microsecond > 0
# ISO format string
dt = parse_datetime("2021-01-01T00:00:00")
assert dt.year == 2021 and dt.month == 1
# ISO format with timezone
dt = parse_datetime("2021-01-01T00:00:00+00:00")
assert dt.tzinfo is not None
Note
String parsing uses datetime.fromisoformat(), which supports ISO 8601 format: "YYYY-MM-DD[T]HH:MM:SS[.ffffff][+HH:MM]"
Source code in src/morphic/string.py
now(**kwargs) -> str
¶
Get the current datetime as a formatted string.
Convenience function that combines datetime.now() with readable_datetime().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Passed to readable_datetime(). Supports: - human (bool): Human-readable format - microsec (bool): Include microseconds - tz (bool): Include timezone |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
Formatted string representation of the current datetime. |
Examples:
# Default format (ISO 8601 with microseconds and timezone)
# "2021-01-01T12:30:45.123456+00:00"
current = now()
# Human-readable format
# "01Jan2021-12:30:45+UTC"
current = now(human=True)
# Without microseconds
# "2021-01-01T12:30:45+00:00"
current = now(microsec=False)
# Without timezone
# "2021-01-01T12:30:45.123456"
current = now(tz=False)
See Also
readable_datetime() for full formatting options.
Source code in src/morphic/string.py
readable_datetime(dt: datetime, *, human: bool = False, microsec: bool = True, tz: bool = True) -> str
¶
Format a datetime object as a readable string.
Provides flexible datetime formatting with options for human-readable output, microsecond precision, and timezone information. Useful for logging, timestamps, and displaying dates to users.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
datetime
|
The datetime object to format. |
required |
human
|
bool
|
If True, uses human-readable format (e.g., "01Jan2021-12:30:45"). If False, uses ISO 8601 format. Defaults to False. |
False
|
microsec
|
bool
|
If True, includes microseconds. Automatically False when human=True. Defaults to True. |
True
|
tz
|
bool
|
If True, includes timezone information. Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
str
|
Formatted datetime string. |
Examples:
from datetime import datetime
dt = datetime(2021, 1, 15, 14, 30, 45, 123456)
# Default: ISO 8601 with microseconds and timezone
# "2021-01-15T14:30:45.123456+00:00"
assert readable_datetime(dt).startswith("2021-01-15T14:30:45")
# Human-readable format
# "15Jan2021-14:30:45+UTC"
readable_datetime(dt, human=True)
# Without microseconds
# "2021-01-15T14:30:45+00:00"
readable_datetime(dt, microsec=False)
# Without timezone
# "2021-01-15T14:30:45.123456"
readable_datetime(dt, tz=False)
# Human without timezone
# "15Jan2021-14:30:45"
readable_datetime(dt, human=True, tz=False)
Note
When human=True, microsec is automatically set to False. The timezone is automatically determined from the datetime object.
Source code in src/morphic/string.py
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 | |
fuzzy_match(string: str, strings_to_match: Union[str, List[str]], *, replacements: Tuple[str, ...] = (SPACE, HYPHEN, SLASH), repl_char: str = UNDERSCORE) -> Optional[str]
¶
Find a fuzzy match for a string from a list of candidates.
Performs case-insensitive matching with character replacements to handle different naming conventions (e.g., "my_file", "my-file", "my file" all match). Returns the original string from the list if matched, or None if no match found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
string
|
str
|
The string to match. |
required |
strings_to_match
|
Union[str, List[str]]
|
A string or list of strings to search through. |
required |
replacements
|
Tuple[str, ...]
|
Characters to normalize (replace with repl_char) before matching. Defaults to (SPACE, HYPHEN, SLASH) = (" ", "-", "/"). |
(SPACE, HYPHEN, SLASH)
|
repl_char
|
str
|
Character to use as replacement. Defaults to "_" (underscore). |
UNDERSCORE
|
Returns:
| Type | Description |
|---|---|
Optional[str]
|
The original matching string from strings_to_match, or None if no match. |
Examples:
# Basic matching with different delimiters
assert fuzzy_match("my_file", ["my-file", "other"]) == "my-file"
assert fuzzy_match("my-file", ["my_file", "other"]) == "my_file"
assert fuzzy_match("my file", ["my_file", "other"]) == "my_file"
# Case-insensitive
assert fuzzy_match("MyFile", ["my_file"]) == "my_file"
assert fuzzy_match("MY-FILE", ["my_file"]) == "my_file"
# No match
assert fuzzy_match("notfound", ["my_file", "other"]) is None
# Single string (not a list)
assert fuzzy_match("my_file", "my-file") == "my-file"
assert fuzzy_match("wrong", "my-file") is None
# Custom replacements
assert fuzzy_match("a.b.c", ["a_b_c"], replacements=(".",)) == "a_b_c"
Note
This function is useful for matching configuration keys, command names, or filenames where users might use different conventions.
Source code in src/morphic/string.py
1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 | |
is_fuzzy_match(string: str, strings_to_match: Union[str, List[str]]) -> bool
¶
Check if a string has a fuzzy match in a list of candidates.
Convenience function that returns True if fuzzy_match() finds a match, False otherwise. Useful for validation and conditional logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
string
|
str
|
The string to check. |
required |
strings_to_match
|
Union[str, List[str]]
|
A string or list of strings to search through. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if a fuzzy match is found, False otherwise. |
Examples:
# Has match
assert is_fuzzy_match("my_file", ["my-file", "other"]) is True
assert is_fuzzy_match("MY-FILE", ["my_file"]) is True
# No match
assert is_fuzzy_match("notfound", ["my_file", "other"]) is False
# Validation example
valid_options = ["enable", "disable", "auto"]
user_input = "en-able"
if is_fuzzy_match(user_input, valid_options):
matched = fuzzy_match(user_input, valid_options)
print(f"Matched: {matched}")
See Also
fuzzy_match() for getting the actual matched string.
Source code in src/morphic/string.py
is_stream(obj) -> bool
¶
Check if an object is a file-like stream.
Determines whether an object is a readable stream (file object, StringIO, etc.) by checking if it inherits from io.IOBase and has a read() method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
The object to check. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the object is a readable stream, False otherwise. |
Examples:
import io
# File object
with open("file.txt", "r") as f:
assert is_stream(f) is True
# StringIO
stream = io.StringIO("content")
assert is_stream(stream) is True
# BytesIO
stream = io.BytesIO(b"content")
assert is_stream(stream) is True
# Not a stream
assert is_stream("string") is False
assert is_stream(123) is False
assert is_stream([1, 2, 3]) is False
assert is_stream(None) is False
Note
This is useful for functions that accept either file paths or file-like objects, allowing flexible input handling.