A lightweight library for type checking and type casting annotated vars.
Project description
annotyped
Annotyped is a simple library with utilities and decorators for type checking and type casting automatically on annotated functions at runtime.
The basics
# Simple typecheck
@annotyped.check
def add(a: int, b: int) -> int:
return a + b
add(1, 2) # 3
add(2, '10') # Param 'b' requires type '<class 'int'>', found '<class 'str'>': '10'
# Simple typecast, annotyped has pythons built in types as standard.
# You can add custom ones (shown later)
@annotyped.cast()
def add(a: int, b: int) -> str:
return a + b
add('10', '20') # '30'
add(1, 2) # '3'
add('1.1', 2) # Param 'a' could not convert to '<class 'int'>' from '<class 'str'>': invalid literal for int() with base 10: '1.1'
Custom converters / casters
@annotyped.cast()
takes named params for each custom converter.
eg:
Convert from a tuple or a str into namedtuple.
import annotyped
import math
from collections import namedtuple
Position = namedtuple('Position', 'x, y')
def position(pos):
if isinstance(pos, str) and ',' in pos:
pos = map(int, pos.split(','))
return Position(*pos)
@annotyped.cast(position=position)
def diff(p1: position, p2: position):
return math.sqrt((p2.x - p1.x)**2 + (p2.y - p1.y)**2)
p1 = (10, 20)
p2 = '20,50'
print( diff(p1, p2) )
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
annotyped-0.1.1.tar.gz
(3.5 kB
view hashes)
Built Distribution
Close
Hashes for annotyped-0.1.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 7dbf529fc103ecb3e08e6f4a26f06e8f8fa9b66859acddfae641d96c4fa43004 |
|
MD5 | 7ccf51500a32bbf2b9f522e0c9960d5a |
|
BLAKE2b-256 | 6b7de7134b81d76ac1398fb4e8d4676c986d0ffadb024090c21cb218a2a940c1 |