File: _dictionary.py

package info (click to toggle)
python-typepy 1.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 624 kB
  • sloc: python: 2,886; makefile: 78; sh: 7
file content (26 lines) | stat: -rw-r--r-- 655 bytes parent folder | download | duplicates (2)
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
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

import json

from ..error import TypeConversionError
from ._interface import AbstractValueConverter


class DictionaryConverter(AbstractValueConverter):
    def force_convert(self):
        try:
            return dict(self._value)
        except (TypeError, ValueError):
            pass

        if isinstance(self._value, str):
            try:
                return json.loads(self._value)
            except json.JSONDecodeError:
                pass

        raise TypeConversionError(
            f"failed to force_convert to dictionary: type={type(self._value)}"
        )