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.0.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.0-py3-none-any.whl (11.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: charded-1.0.0.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.0.tar.gz
Algorithm Hash digest
SHA256 29bd1ccf67278ab495affa359027b9f58c70aa52c798beacef6e38b2bf57c477
MD5 5e6ad3fd00dcd2ce172808717e6b2574
BLAKE2b-256 47a790aef730575459dfd251f36ffb9e75670ca4b47ee6059b9f9404bc3aae68

See more details on using hashes here.

File details

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

File metadata

  • Download URL: charded-1.0.0-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.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f6648b17746cb953b19b7d39f21a25714bb298fe72dd460bbcf4a38fa95386fb
MD5 703d5b5c24129fab0d02f25bdc0b006b
BLAKE2b-256 67b9c2bb6a9fb3791b065bac9c885ee6c0b74562705efa05c9eb3eadc3467ec0

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