TypeDict
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 defaultpop(key, default=None): Remove and return valuesetdefault(key, default=None): Set default if key doesn't existupdate(other, **kwargs): Update from dict or kwargskeys(): Return view of type keysvalues(): Return view of valuesitems(): Return view of (type, value) pairsget_types(): Return list of all types used as keyshas_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
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- 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
Metadata
Release files for typedict 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| typedict-0.1.0.tar.gz | 9.3 kB | Without provenance | Details for typedict-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| typedict-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for typedict-0.1.0-py3-none-any.whl |
Total release size: 15.9 kB
Release files / typedict-0.1.0.tar.gz
| Download URL | typedict-0.1.0.tar.gz |
|---|---|
| Size | 9.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d66a300f1d0b8e596b930d1a892dc95171de539b414cb8971b9b70826181de51
|
|
BLAKE2b-256 checksum How to use checksums |
89cc6605fe716f4837230d6fae81443ca7da2213c943626c2169b9c57ad88249
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.13
|
Release files / typedict-0.1.0-py3-none-any.whl
| Download URL | typedict-0.1.0-py3-none-any.whl |
|---|---|
| Size | 6.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
361be2b0155e7ef3debfaeec504655f7b1faa74ee89c36eead61c99425ca3a26
|
|
BLAKE2b-256 checksum How to use checksums |
286796f1c2c1ab25ffd2d930b7f02810444d141530fc29428e5a5ec4fe2812ef
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.13
|
Security for typedict 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.