File: dataclass_postponed_annotations.py

package info (click to toggle)
python-omegaconf 2.3.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,244 kB
  • sloc: python: 26,413; makefile: 38; sh: 11
file content (56 lines) | stat: -rw-r--r-- 1,516 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# `from __future__` has to be the very first thing in a module
# otherwise a syntax error is raised
from __future__ import annotations  # noqa  # Python 3.6 linters complain

from dataclasses import dataclass, fields
from enum import Enum
from pathlib import Path

from pytest import raises

from omegaconf import OmegaConf, ValidationError


class Height(Enum):
    SHORT = 0
    TALL = 1


@dataclass
class SimpleTypes:
    num: int = 10
    pi: float = 3.1415
    is_awesome: bool = True
    height: "Height" = Height.SHORT  # test forward ref
    description: str = "text"
    data: bytes = b"bin_data"
    path: Path = Path("hello.txt")


def simple_types_class() -> None:
    # confirm that the type annotations are in fact stored as strings
    # i.e., that the `from future` import worked
    num_field = fields(SimpleTypes)[0]
    assert isinstance(num_field.type, str)
    assert num_field.type == "int"

    conf = OmegaConf.structured(SimpleTypes)
    assert conf.num == 10
    assert conf.pi == 3.1415
    assert conf.data == b"bin_data"
    assert conf.path == Path("hello.txt")
    assert conf.is_awesome is True
    assert conf.height == Height.SHORT
    assert conf.description == "text"


def conversions() -> None:
    conf: SimpleTypes = OmegaConf.structured(SimpleTypes)
    conf.num = 20

    conf.num = "20"  # type: ignore
    assert conf.num == 20

    with raises(ValidationError):
        # ValidationError: "one" cannot be converted to an integer
        conf.num = "one"  # type: ignore