File: undefined.py

package info (click to toggle)
python-tatsu 5.17.1%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 1,516 kB
  • sloc: python: 13,185; makefile: 127
file content (61 lines) | stat: -rw-r--r-- 1,353 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# Copyright (c) 2017-2026 Juancarlo AƱez (apalala@gmail.com)
# SPDX-License-Identifier: BSD-4-Clause
from __future__ import annotations

from typing import Any, cast

__all__ = ['UndefinedType', 'Undefined', 'notnone']


def notnone[T](value: T | None, default: T) -> T:
    return value if value is not None else default


class UndefinedType[T]:
    __notnone: Any = None

    def __init__(self):
        if isinstance(self.__notnone, UndefinedType):
            return
        type(self).__notnone = self

    @classmethod
    def notnone(cls) -> UndefinedType[T]:
        return cast(UndefinedType[T], cls.__notnone)

    def __eq__(self, other: Any) -> bool:
        if self is not Undefined:
            return False
        if other is not Undefined:
            return False
        return other is self

    def __bool__(self):
        return False

    def __and__(self, other):
        return self

    def __rand__(self, other):
        return self.__and__(other)

    def __or__(self, other):
        return other

    def __ror__(self, other):
        return self.__or__(other)

    def __invert__(self):
        return not None

    def __repr__(self) -> str:
        return 'Undefined'

    def __str__(self) -> str:
        return 'Undefined'

    def __hash__(self) -> int:
        return hash(id(self))


Undefined = UndefinedType()