Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/succhiello/typedtuple
namedtuple with type definition
https://github.com/succhiello/typedtuple
Last synced: 4 months ago
JSON representation
namedtuple with type definition
- Host: GitHub
- URL: https://github.com/succhiello/typedtuple
- Owner: succhiello
- License: other
- Created: 2015-12-28T09:29:39.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2017-09-30T20:36:13.000Z (over 7 years ago)
- Last Synced: 2024-10-08T14:21:00.835Z (5 months ago)
- Language: Python
- Size: 9.77 KB
- Stars: 3
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.rst
- License: LICENSE
Awesome Lists containing this project
README
typedtuple
==========install
-------::
$ pip install typedtuple
basic definition
----------------.. code:: python
from typedtuple import typedtuple
# definition dictionary is converted to voluptuous.Schema(definition_dict, required=True)
Vector = typedtuple('Vector', {'x': float, 'y': float, 'z': float})
v0 = Vector(x=10.0, y=20.0, z=30.0)
print v0.x # 10.0
v1 = Vector(x=10, y=20) # raises exceptionusing voluptuous schema
-----------------------.. code:: python
from voluptuous import Schema
# can use voluptuous.Schema as definition
Vector = typedtuple('Vector', Schema({'x': float, 'y': float, 'z': float}, required=True))using @schema decorator
-----------------------.. code:: python
from math import sqrt
from typedtuple import schema@schema({'x': float, 'y': float, 'z': float})
class Vector(object):
@property
def length(self):
return sqrt(pow(self.x, 2.0) + pow(self.y, 2.0) + pow(self.z, 2.0))v = Vector(x=1.0, y=2.0, z=2.0)
print v.length # 3.0using voluptuous functions
--------------------------.. code:: python
from voluptuous import Coerce
from typedtuple import schema@schema({'x': Coerce(float), 'y': Coerce(float)})
class Vector(object):
passv0 = Vector(x=10, y='20.0')
print v0.x # 10.0
print v0.y # 20.0using OrderedDict
-----------------.. code:: python
from collections import OrderedDict
from typedtuple import schema@schema(OrderedDict((('x', float), ('y', float), ('z', float))))
class Vector(object):
passprint Vector._fields # ('x', 'y', 'z')
caveat
------TypedTuple is tuple. so...
.. code:: python
from collections import OrderedDict
from typedtuple import typedtupleVector0 = typedtuple('Vector0', OrderedDict((('x', float), ('y', float))))
Vector1 = typedtuple('Vector1', OrderedDict((('y', float), ('x', float))))v0 = Vector0(x=10.0, y=20.0)
v1 = Vector1(x=20.0, y=10.0)
v0 == v1 # TrueTODO
----use nose for test
benchmark