- Notifications
You must be signed in to change notification settings - Fork0
Automatic (de)serialization of arguments and return values for Python functions
License
alexmojaki/datafunctions
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Automatic (de)serialization of arguments and return values for Python functions.
pip install datafunctions
@datafunction
is a decorator which automatically deserializes incoming arguments of the decorated function andserializes the return value. For example:
fromdatetimeimportdatetimefromdatafunctionsimportdatafunction@datafunctiondefnext_year(dt:datetime)->datetime:returndt.replace(year=dt.year+1)assertnext_year("2019-01-02T00:00:00")=="2020-01-02T00:00:00"
@datafunction
automatically converts the string argument to a datetime object, and thenconverts the returned datetime back to a string.
This is useful for calling functions over a remote connection or from a different language - seeinstant_api andinstant_client for example.
More generally, the arguments and return value as seen from the outside the functionare basic JSON serializable objects - strings, dicts, etc.They are converted to and from the correct types (as indicated by type annotations)bymarshmallow. Common Python types as well as dataclasses (which may be nested)are supported. For example:
fromdataclassesimportdataclassfromdatafunctionsimportdatafunction@dataclassclassPoint:x:inty:int@datafunctiondeftranslate(p:Point,dx:int,dy:int)->Point:returnPoint(p.x+dx,p.y+dy)asserttranslate({"x":1,"y":2},3,4)== {"x":4,"y":6}
To decorate a method, passis_method=True
, e.g:
classMyClass:@datafunction(is_method=True)defmethod(self,x:int)->int: ...
All parameters and the return value must have a type annotation,except for the first argument whenis_method=True
.Variadic parameters (e.g.*args
or**kwargs
) and positional-only parameters (before/
)are not allowed.
If there is an exception deserializing or binding the arguments anArgumentError
will be raised with the underlying exception attached to__cause__
.Similarly aReturnError
may be raised when trying to serialize the return value.
For more manual control, use the methods:
load_arguments
dump_arguments
load_result
dump_result
Under the hood, the type annotations are gathered into adataclass which is thenconverted into amarshmallow schemausingmarshmallow_dataclass.marshmallow handles the (de)serialization.
Instances of this class have attributesparams_schemas
andreturn_schemas
,each of which have the following attributes:
dataclass
schema_class
: the marshmallow schema classschema_instance
: a no-args instance of schema_class
About
Automatic (de)serialization of arguments and return values for Python functions
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.