File: decimal.py

package info (click to toggle)
python-graphene 3.4.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,120 kB
  • sloc: python: 8,935; makefile: 214; sh: 18
file content (34 lines) | stat: -rw-r--r-- 861 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from decimal import Decimal as _Decimal

from graphql import Undefined
from graphql.language.ast import StringValueNode, IntValueNode

from .scalars import Scalar


class Decimal(Scalar):
    """
    The `Decimal` scalar type represents a python Decimal.
    """

    @staticmethod
    def serialize(dec):
        if isinstance(dec, str):
            dec = _Decimal(dec)
        assert isinstance(
            dec, _Decimal
        ), f'Received not compatible Decimal "{repr(dec)}"'
        return str(dec)

    @classmethod
    def parse_literal(cls, node, _variables=None):
        if isinstance(node, (StringValueNode, IntValueNode)):
            return cls.parse_value(node.value)
        return Undefined

    @staticmethod
    def parse_value(value):
        try:
            return _Decimal(value)
        except Exception:
            return Undefined