Skip to main content

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.

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.2.tar.gz (23.8 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.2-py3-none-any.whl (11.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: charded-1.0.2.tar.gz
  • Upload date:
  • Size: 23.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.12.3 {"installer":{"name":"uv","version":"0.12.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.2.tar.gz
Algorithm Hash digest
SHA256 7f75ae768600e6f3cd7a3736991c312bc0b64079e2e078fceb4af3102ff0aa09
MD5 137f6eefd5d53b37e2318569c6273fc5
BLAKE2b-256 41f33196043e09f150e3b523a07ef8550338a0f5d357f9ae84d0a3ed96f17e1a

See more details on using hashes here.

File details

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

File metadata

  • Download URL: charded-1.0.2-py3-none-any.whl
  • Upload date:
  • Size: 11.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.12.3 {"installer":{"name":"uv","version":"0.12.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.2-py3-none-any.whl
Algorithm Hash digest
SHA256 2175093027eb0263eceab236159f2fd93c7304fb7dd0b91554a0cf17c1c5a4e9
MD5 3a0eabbf71037c314705af73c0c2d6ea
BLAKE2b-256 970b1a2f30947402f4b8d5c6979e53b6be011bc8740a46e2e3882ded3189290b

See more details on using hashes here.

Release history Release notifications | RSS feed

1.2.0

2 files

1.1.1

2 files

1.1.0

2 files

1.0.4

2 files

1.0.3

2 files

This release

1.0.2 This release

2 files

1.0.1

2 files

1.0.0

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page