Skip to main content

A dict that only uses types as keys. Converts keys used to their type.

Project description

TypeDict

Tests PyPI version Python versions License: MIT Code style: ruff

A dictionary that uses types as keys, automatically converting values to their types.

Features

  • Type-based keys: Automatically converts any key to its type
  • Full dict compatibility: Supports all standard dictionary methods
  • Type safety: Full type hints and mypy support
  • Modern Python: Requires Python 3.11+
  • Comprehensive testing: 100% test coverage

Installation

pip install typedict

Quick Start

from typedict import TypeDict

# Create a TypeDict
td = TypeDict()

# Set values - keys are automatically converted to their types
td[42] = "hello"        # Key becomes int
td["world"] = 123       # Key becomes str
td[3.14] = "pi"         # Key becomes float

# Access values using either the original key or the type
print(td[int])          # "hello"
print(td[42])           # "hello" (same as above)
print(td[str])          # 123
print(td["test"])       # 123 (same as above)

# Type keys overwrite value keys
td[int] = "type_key"
print(td[42])           # "type_key" (now uses the type key)

Use Cases

Configuration by Type

from typedict import TypeDict

# Store configuration values by type
config = TypeDict()
config[42] = "port"
config["localhost"] = "host"
config[True] = "debug_mode"

# Access configuration
port = config[int]      # "port"
host = config[str]      # "localhost"
debug = config[bool]    # "debug_mode"

Type-based Caching

from typedict import TypeDict
import time

cache = TypeDict()

def expensive_operation(data_type):
    if data_type in cache:
        return cache[data_type]
    
    # Simulate expensive operation
    time.sleep(1)
    result = f"processed_{data_type.__name__}"
    cache[data_type] = result
    return result

# First call - expensive
result1 = expensive_operation(int)    # Takes 1 second

# Second call - cached
result2 = expensive_operation(int)   # Instant!

Serialization by Type

from typedict import TypeDict
import json

serializers = TypeDict()
serializers[int] = lambda x: str(x)
serializers[str] = lambda x: f'"{x}"'
serializers[list] = lambda x: json.dumps(x)

def serialize(data):
    data_type = type(data)
    serializer = serializers.get(data_type, str)
    return serializer(data)

print(serialize(42))           # "42"
print(serialize("hello"))      # '"hello"'
print(serialize([1, 2, 3]))    # "[1, 2, 3]"

API Reference

TypeDict

A dictionary that uses types as keys.

Methods

  • __getitem__(key): Get value for key (converted to type)
  • __setitem__(key, value): Set value for key (converted to type)
  • __delitem__(key): Delete key (converted to type)
  • __contains__(key): Check if key exists (converted to type)
  • get(key, default=None): Get value with default
  • pop(key, default=None): Remove and return value
  • setdefault(key, default=None): Set default if key doesn't exist
  • update(other, **kwargs): Update from dict or kwargs
  • keys(): Return view of type keys
  • values(): Return view of values
  • items(): Return view of (type, value) pairs
  • get_types(): Return list of all types used as keys
  • has_type(type_key): Check if type exists as key

Special Behavior

  • Type conversion: All keys are automatically converted to their types
  • Type precedence: Using a type directly as a key overwrites any value keys of that type
  • Collision handling: Multiple values of the same type overwrite each other (last wins)

Examples

Basic Operations

from typedict import TypeDict

td = TypeDict()

# Set values
td[42] = "integer"
td["hello"] = "string"
td[3.14] = "float"
td[True] = "boolean"

# Access values
print(td[int])      # "integer"
print(td[str])      # "string"
print(td[float])    # "float"
print(td[bool])     # "boolean"

# Type keys overwrite value keys
td[int] = "type_key"
print(td[42])       # "type_key" (not "integer")

Dictionary Methods

from typedict import TypeDict

td = TypeDict()
td[42] = "hello"
td["world"] = 123

# Standard dict methods work
print(len(td))              # 2
print(int in td)            # True
print(td.get(str, "default"))  # 123
print(td.pop(int))          # "hello"
print(td.get(int, "missing"))  # "missing"

# Type-specific methods
print(td.get_types())       # [<class 'str'>]
print(td.has_type(int))     # False
print(td.has_type(str))     # True

Edge Cases

from typedict import TypeDict

td = TypeDict()

# None handling
td[None] = "none_value"
print(td[type(None)])  # "none_value"

# Custom classes
class MyClass:
    pass

instance = MyClass()
td[instance] = "custom"
print(td[MyClass])      # "custom"

# Type vs value collision
td[42] = "value_key"
td[int] = "type_key"
print(td[42])           # "type_key" (type key wins)

Development

Setup

git clone https://github.com/eddiethedean/typedict.git
cd typedict
pip install -e .[dev]

Running Tests

pytest

Code Quality

ruff check src tests
mypy src

Pre-commit Hooks

pre-commit install
pre-commit run --all-files

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog

0.1.0 (2024-01-XX)

  • BREAKING: Minimum Python version is now 3.11
  • NEW: Complete rewrite with modern type hints
  • NEW: Added all standard dict methods (get, pop, setdefault, etc.)
  • NEW: Added type-specific methods (get_types, has_type)
  • NEW: Comprehensive test suite with 97% coverage
  • NEW: GitHub Actions CI/CD pipeline
  • NEW: Modern build system with pyproject.toml
  • NEW: Pre-commit hooks and code quality tools
  • IMPROVED: Better error handling and edge case support
  • IMPROVED: Enhanced documentation and examples

0.0.3 (Previous)

  • Initial release with basic functionality

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

typedict-0.1.0.tar.gz (9.3 kB view details)

Uploaded Source

Built Distribution

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

typedict-0.1.0-py3-none-any.whl (6.6 kB view details)

Uploaded Python 3

File details

Details for the file typedict-0.1.0.tar.gz.

File metadata

  • Download URL: typedict-0.1.0.tar.gz
  • Upload date:
  • Size: 9.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.13

File hashes

Hashes for typedict-0.1.0.tar.gz
Algorithm Hash digest
SHA256 d66a300f1d0b8e596b930d1a892dc95171de539b414cb8971b9b70826181de51
MD5 49e3d1cfe19c498a69e1ae9cd62463df
BLAKE2b-256 89cc6605fe716f4837230d6fae81443ca7da2213c943626c2169b9c57ad88249

See more details on using hashes here.

File details

Details for the file typedict-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: typedict-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 6.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.13

File hashes

Hashes for typedict-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 361be2b0155e7ef3debfaeec504655f7b1faa74ee89c36eead61c99425ca3a26
MD5 a7947c993c3ecafa0fbdf896bb54bb3e
BLAKE2b-256 286796f1c2c1ab25ffd2d930b7f02810444d141530fc29428e5a5ec4fe2812ef

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