Skip to main content

charded

Project description

charded

Python 3.12+ License: BSD

charded is a type-safe, generic string/bytes container with automatic charset detection. It wraps anything you throw at it — str, bytes, even int — and lets you work with it as either text or raw bytes, without guessing encodings.

Installation

Via uv:

uv add charded

Features

  • Generic type safetyStr[str] or Str[bytes] with compile-time checking
  • Automatic charset detection — combines charset-normalizer, python-magic, and internal heuristics
  • MIME type sniffing — detect content type via libmagic
  • Zero-copy lazy evaluation — cached properties, decode/encode only when needed
  • Full str proxy — use len(), [], split(), startswith(), tokenize(), etc. directly on the container
  • Binary detection — adaptive hybrid sampling strategy for large files
  • Utility functionsto_ascii(), to_bytes(), to_text() for quick conversions

Quick Start

Wrap anything

from charded import Str

# From bytes with unknown encoding
x = Str(b"\xc3\xa9l\xc3\xa8ve")  # UTF-8 French text
print(x.string)   # "élève"
print(x.charset)  # "utf-8"

# From str
y = Str("hello")
print(y.bytes)    # b"hello"

# Or use built-in constructors directly
print(bytes(Str("a")))   # b'a'
print(str(Str(b"asd")))  # "asd"

Automatic charset detection

raw = b"\xef\xf0\xe8\xea"  # some Russian text in unknown encoding
s = Str(raw)

print(s.charset)           # detected encoding, e.g. "cp1251"
print(str(s))              # decoded text
print(bytes(s))            # original bytes

Detection order:

  1. Explicit charset= argument if provided
  2. charset-normalizer result
  3. Internal heuristic scan (adaptive binary-offset sampling)
  4. Fallback to ASCII

MIME type detection

data = Str(b"%PDF-1.4\n1 0 obj")
print(data.mime)
# {"type": "application/pdf", "description": "PDF document, version 1.4"}

Use as a string

Str proxies almost all str methods, so you can use it directly:

s = Str(b"hello world")

len(s)           # 11
s[0:5]           # "hello"
s.split()        # ["hello", "world"]
s.startswith("h")  # True
s.upper()        # "HELLO WORLD"

Tokenize

s = Str("foo-bar_baz, qux")
print(s.tokenize(r"[\w]+"))
# ("foo", "bar", "baz", "qux")

Utility functions

from charded import to_ascii, to_bytes, to_text

# Force ASCII transliteration
text = to_ascii("Café résumé naïve")
# "Cafe resume naive"

# Convert anything to bytes
raw = to_bytes("hello", charset="utf-8")

# Convert anything to text
text = to_text(b"hello", charset="utf-8")

Type Safety

Str is a true generic. Use Str[str] or Str[bytes] for explicit typing:

from charded import Str

def process(data: Str[bytes]) -> str:
    return data.string.upper()

process(Str(b"hello"))   # OK
process(Str("hello"))     # type error (mypy/pyright will catch it)

Type aliases are also provided:

from charded.string import StrBytes, StrText

def load(raw: StrBytes) -> StrText:
    return Str(raw.string)

How charset detection works

For small inputs (< 64 bytes), charded does a full scan. For medium and large inputs it uses an adaptive hybrid binary-offset strategy:

  • Header-heavy sampling — first 1 KB scanned with moderate density
  • Exponential sparse middle — O(log n) samples for large files
  • Footer sampling — last 1 KB checked for trailing signatures

This guarantees detection of BOMs, null-byte injection, and encoding signatures without reading the entire file into memory.


API Reference

Str[T]

Member Type Description
Str.to_bytes(obj, charset=None) classmethod Convert anything to bytes
Str.to_text(obj, charset=None) classmethod Convert anything to str
Str.to_ascii(x, charset=None) staticmethod Transliterate to ASCII
mime property {"type": ..., "description": ...} or None
tokenize(regex) method Regex tokenization, returns tuple[str, ...]

All standard str methods (split, startswith, upper, etc.) are proxied.


License

BSD 3-Clause. See LICENSE for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

charded-1.0.1.tar.gz (23.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

charded-1.0.1-py3-none-any.whl (11.3 kB view details)

Uploaded Python 3

File details

Details for the file charded-1.0.1.tar.gz.

File metadata

  • Download URL: charded-1.0.1.tar.gz
  • Upload date:
  • Size: 23.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.3 {"installer":{"name":"uv","version":"0.11.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for charded-1.0.1.tar.gz
Algorithm Hash digest
SHA256 1243360d3534a8f1f9663ef7c6791e225364b0c9fd385efdd6c6829ac38d73bf
MD5 b987023489aec0af11f828302f5c6f2b
BLAKE2b-256 1622c37a812ba827f2aca6a06129e153674f13d90d7e1f6aa408bdd0de447ea2

See more details on using hashes here.

File details

Details for the file charded-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: charded-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 11.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.3 {"installer":{"name":"uv","version":"0.11.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for charded-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c937bbf61cee4c1d1b6c2a7c938130e76beee6933bb30c223e2527b49429c7de
MD5 1afa0dcd98f07ccbd2a6dde78b441644
BLAKE2b-256 a05bc3809bd914feff7c3d97181f3aa4b60b85e4f2e0724d83736b77f3ee8965

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page