valueparser


Namevalueparser JSON
Version 0.1.5 PyPI version JSON
download
home_page
SummaryPython package for quick creation of tools to parse a value
upload_time2023-01-17 16:08:10
maintainer
docs_urlNone
authorSylvain Guieu
requires_python>=3.7,<4.0
license
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            Parser
======

Python package for quick creation/ combination of value parser object for muly-puposes

Install
=======

```shell
> pip install valueparser
```

Usage
=====

```python
from valueparser.parsers import Bounded

value_parser = Bounded(min=0, max=1)

value_parser.parse(4.0)

# ParseError: 4.0 is higher than 1.0
```

Several parsers can be combined to one single parser object, they share however the same name space for configuration
parameters

```python 
from valueparser import parser, Clipped, Rounded

ratio_parser = parser( (float, Clipped, Rounded),  min=0, max=1.0, ndigits=2 )

assert ratio_parser.parse( 0.231234) == 0.23 
assert ratio_parser.parse( 4.5) == 1.0 
assert ratio_parser.parse( "0.12345") == 0.12

```

Equivalent can be done by creating a new class 

```python 
from valueparser import parser_class, Clipped, Rounded

MyParser = parser_class( (float, Clipped, Rounded), "MyParser" )
ratio_parser = MyParser( min=0, max=1, ndigits=2)
```


`conparser` works the same way than `parser` except it construct a typing object to be use inside pydantic BaseModel in
a compact way.


```python 
from valueparser import conparser, Bounded
from pydantic import BaseModel 

Pixel =  conparser( (int, Bounded), min=0, max=1023 ) 
class Data(BaseModel):
    x: Pixel = 512
    y: Pixel = 512
   
Data(x=-200)

# 
#pydantic.error_wrappers.ValidationError: 1 validation error for Data
#x
#    -200.0 is lower than 0.0 (type=value_error.parse; error_code=Errors.OUT_OF_BOUND)
```

to make any function a `parser` (e.g. an object with `parse` method) one can use the  `parser` function as well :

```python
from valueparser import parser

float_parser = parser(float)
assert float_parser.parse("1.234") == 1.234

force_int_parser = parser( (float, int)) # parse to float then int 
assert force_int_parser.parse( "1.234") == 1
```

Actually the `parser` function accepts :

- A Parser Class iddentified as a class with the `parse` method 
- A callable 
- An instance of a Parser Class
- an mix inside an iterable 

Plus any kwargs accepted by the combination of parsers

Builtin Parsers 
===============

| class name |  kwargs | comment | 
|------------|---------|---------|
| Bounded    | min=-inf, max=+inf | raise an error if value outside interval else return value |
| Clipped    | min=-inf, max=+inf | clip silently the value to inferior and superior bounds | 
| Rounded    | ndigits=0          | round the numerical value to ndigits           |
| Formated   | format="%s"        | convert to string with the given format        |
| Listed     | items=[], default_item(optional) |  raise error if value not in items list else return value a
|            |                                  | default_item can be set to be returned instead of error raised |
| Enumerated  | enumerator                        | return enumerator(value) or raise error | 


Create a custom parser
======================

To create a parser one need to create a new class from BaseParser, declare any configurable argument 
inside the child class ``Config``  and define the static or classmethod `__parse__`

For instance a parser adding some noise to a value ( can be usefull for e.i. a simulator) 

```python
from valueparser import BaseParser
import random 

class Noisier(BaseParser):
    class Config:
        noise_scale = 1.0
    @staticmethod
    def __parse__( value, config):
        return value + (random.random()-0.5) * config.noise_scale
```

Usage : 

```python
noisier = Noisier( noise_scale=100)
x = noisier.parse(0.0)
x
36.700125482238036
```

Or use conparser in pydantic Model: 

```python 
from valueparser import conparser 
from pydantic import BaseModel  

class MyData(BaseModel):
    x: conparser(Noisier, noise_scale=100)
    y: conparser(Noisier, noise_scale=100)

my_data = MyData(x=0, y=0)
my_data
MyData(x=32.819723479459284, y=-25.95893228872207)
```


Parser and Systemy 
==================

Parsers are beased on :class:`systemy.System` class. One can include a parser factory in 
a systemy class and expose the parser configuration to user. 

```python 
from valueparser import ParserFactory , Bounded
from systemy import BaseSystem 
from pydantic import AnyUrl 

dummy = lambda x:x 

class Node(BaseSystem):
    class Config:
        url: AnyUrl = "http://localhost:4840"
        parser: ParserFactory = ParserFactory(type=dummy)

    def set(self, value):
        value = self.parser.parse(value) 
        # set value on server 
        return value

node = Node( parser={'type':(float,Bounded), 'min':0, 'max':10} )
```








            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "valueparser",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7,<4.0",
    "maintainer_email": "",
    "keywords": "",
    "author": "Sylvain Guieu",
    "author_email": "sylvain.guieu@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/cf/ea/4436030ce7426847bd1f9691c3386014a74361142dd8550141f81b179e5b/valueparser-0.1.5.tar.gz",
    "platform": null,
    "description": "Parser\n======\n\nPython package for quick creation/ combination of value parser object for muly-puposes\n\nInstall\n=======\n\n```shell\n> pip install valueparser\n```\n\nUsage\n=====\n\n```python\nfrom valueparser.parsers import Bounded\n\nvalue_parser = Bounded(min=0, max=1)\n\nvalue_parser.parse(4.0)\n\n# ParseError: 4.0 is higher than 1.0\n```\n\nSeveral parsers can be combined to one single parser object, they share however the same name space for configuration\nparameters\n\n```python \nfrom valueparser import parser, Clipped, Rounded\n\nratio_parser = parser( (float, Clipped, Rounded),  min=0, max=1.0, ndigits=2 )\n\nassert ratio_parser.parse( 0.231234) == 0.23 \nassert ratio_parser.parse( 4.5) == 1.0 \nassert ratio_parser.parse( \"0.12345\") == 0.12\n\n```\n\nEquivalent can be done by creating a new class \n\n```python \nfrom valueparser import parser_class, Clipped, Rounded\n\nMyParser = parser_class( (float, Clipped, Rounded), \"MyParser\" )\nratio_parser = MyParser( min=0, max=1, ndigits=2)\n```\n\n\n`conparser` works the same way than `parser` except it construct a typing object to be use inside pydantic BaseModel in\na compact way.\n\n\n```python \nfrom valueparser import conparser, Bounded\nfrom pydantic import BaseModel \n\nPixel =  conparser( (int, Bounded), min=0, max=1023 ) \nclass Data(BaseModel):\n    x: Pixel = 512\n    y: Pixel = 512\n   \nData(x=-200)\n\n# \n#pydantic.error_wrappers.ValidationError: 1 validation error for Data\n#x\n#    -200.0 is lower than 0.0 (type=value_error.parse; error_code=Errors.OUT_OF_BOUND)\n```\n\nto make any function a `parser` (e.g. an object with `parse` method) one can use the  `parser` function as well :\n\n```python\nfrom valueparser import parser\n\nfloat_parser = parser(float)\nassert float_parser.parse(\"1.234\") == 1.234\n\nforce_int_parser = parser( (float, int)) # parse to float then int \nassert force_int_parser.parse( \"1.234\") == 1\n```\n\nActually the `parser` function accepts :\n\n- A Parser Class iddentified as a class with the `parse` method \n- A callable \n- An instance of a Parser Class\n- an mix inside an iterable \n\nPlus any kwargs accepted by the combination of parsers\n\nBuiltin Parsers \n===============\n\n| class name |  kwargs | comment | \n|------------|---------|---------|\n| Bounded    | min=-inf, max=+inf | raise an error if value outside interval else return value |\n| Clipped    | min=-inf, max=+inf | clip silently the value to inferior and superior bounds | \n| Rounded    | ndigits=0          | round the numerical value to ndigits           |\n| Formated   | format=\"%s\"        | convert to string with the given format        |\n| Listed     | items=[], default_item(optional) |  raise error if value not in items list else return value a\n|            |                                  | default_item can be set to be returned instead of error raised |\n| Enumerated  | enumerator                        | return enumerator(value) or raise error | \n\n\nCreate a custom parser\n======================\n\nTo create a parser one need to create a new class from BaseParser, declare any configurable argument \ninside the child class ``Config``  and define the static or classmethod `__parse__`\n\nFor instance a parser adding some noise to a value ( can be usefull for e.i. a simulator) \n\n```python\nfrom valueparser import BaseParser\nimport random \n\nclass Noisier(BaseParser):\n    class Config:\n        noise_scale = 1.0\n    @staticmethod\n    def __parse__( value, config):\n        return value + (random.random()-0.5) * config.noise_scale\n```\n\nUsage : \n\n```python\nnoisier = Noisier( noise_scale=100)\nx = noisier.parse(0.0)\nx\n36.700125482238036\n```\n\nOr use conparser in pydantic Model: \n\n```python \nfrom valueparser import conparser \nfrom pydantic import BaseModel  \n\nclass MyData(BaseModel):\n    x: conparser(Noisier, noise_scale=100)\n    y: conparser(Noisier, noise_scale=100)\n\nmy_data = MyData(x=0, y=0)\nmy_data\nMyData(x=32.819723479459284, y=-25.95893228872207)\n```\n\n\nParser and Systemy \n==================\n\nParsers are beased on :class:`systemy.System` class. One can include a parser factory in \na systemy class and expose the parser configuration to user. \n\n```python \nfrom valueparser import ParserFactory , Bounded\nfrom systemy import BaseSystem \nfrom pydantic import AnyUrl \n\ndummy = lambda x:x \n\nclass Node(BaseSystem):\n    class Config:\n        url: AnyUrl = \"http://localhost:4840\"\n        parser: ParserFactory = ParserFactory(type=dummy)\n\n    def set(self, value):\n        value = self.parser.parse(value) \n        # set value on server \n        return value\n\nnode = Node( parser={'type':(float,Bounded), 'min':0, 'max':10} )\n```\n\n\n\n\n\n\n\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "Python package for quick creation of tools to parse a value",
    "version": "0.1.5",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "225d71fcf9393feba2cf648b389b0ef35bc32ca92acbea89f9e8b2c14557e3c3",
                "md5": "8cc8de05f62f6f3709e4195e982e380e",
                "sha256": "c4af4a5c50afde8e43e719a34a2e6a19ef881d0e3adde49ea077451c5eab9e20"
            },
            "downloads": -1,
            "filename": "valueparser-0.1.5-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "8cc8de05f62f6f3709e4195e982e380e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7,<4.0",
            "size": 7660,
            "upload_time": "2023-01-17T16:08:08",
            "upload_time_iso_8601": "2023-01-17T16:08:08.826794Z",
            "url": "https://files.pythonhosted.org/packages/22/5d/71fcf9393feba2cf648b389b0ef35bc32ca92acbea89f9e8b2c14557e3c3/valueparser-0.1.5-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "cfea4436030ce7426847bd1f9691c3386014a74361142dd8550141f81b179e5b",
                "md5": "893dea681daacf5b001e549480470517",
                "sha256": "961e2d72ff7973c62e27fce5d23a999aad7a1c3d1dd5f9acf3ef62d454342152"
            },
            "downloads": -1,
            "filename": "valueparser-0.1.5.tar.gz",
            "has_sig": false,
            "md5_digest": "893dea681daacf5b001e549480470517",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7,<4.0",
            "size": 7848,
            "upload_time": "2023-01-17T16:08:10",
            "upload_time_iso_8601": "2023-01-17T16:08:10.325026Z",
            "url": "https://files.pythonhosted.org/packages/cf/ea/4436030ce7426847bd1f9691c3386014a74361142dd8550141f81b179e5b/valueparser-0.1.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-01-17 16:08:10",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "valueparser"
}
        
Elapsed time: 0.11038s