Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1#!/usr/bin/env python 

2# cardinal_pythonlib/typetests.py 

3 

4""" 

5=============================================================================== 

6 

7 Original code copyright (C) 2009-2021 Rudolf Cardinal (rudolf@pobox.com). 

8 

9 This file is part of cardinal_pythonlib. 

10 

11 Licensed under the Apache License, Version 2.0 (the "License"); 

12 you may not use this file except in compliance with the License. 

13 You may obtain a copy of the License at 

14 

15 https://www.apache.org/licenses/LICENSE-2.0 

16 

17 Unless required by applicable law or agreed to in writing, software 

18 distributed under the License is distributed on an "AS IS" BASIS, 

19 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

20 See the License for the specific language governing permissions and 

21 limitations under the License. 

22 

23=============================================================================== 

24 

25**Short functions to test the type/value of an object.** 

26 

27""" 

28 

29from typing import Any, Iterable 

30 

31 

32# ============================================================================= 

33# Testers/validators 

34# ============================================================================= 

35 

36def is_integer(s: Any) -> bool: 

37 """ 

38 Is the parameter an integer? 

39 """ 

40 try: 

41 int(s) 

42 return True 

43 except ValueError: 

44 return False 

45 

46 

47def raise_if_attr_blank(obj: Any, attrs: Iterable[str]) -> None: 

48 """ 

49 Raise an :exc:`Exception` if any of the attributes of ``obj`` named in 

50 ``attrs`` is ``None`` or is ``''``. 

51 """ 

52 for a in attrs: 

53 value = getattr(obj, a) 

54 if value is None or value is "": 

55 raise Exception(f"Blank attribute: {a}") 

56 

57 

58# ============================================================================= 

59# bool 

60# ============================================================================= 

61 

62def is_false(x: Any) -> bool: 

63 """ 

64 Positively false? Evaluates: ``not x and x is not None``. 

65 """ 

66 # beware: "0 is False" evaluates to False -- AVOID "is False"! 

67 # ... but "0 == False" evaluates to True 

68 # https://stackoverflow.com/questions/3647692/ 

69 # ... but comparisons to booleans with "==" fail PEP8: 

70 # http://legacy.python.org/dev/peps/pep-0008/ 

71 # ... so use e.g. "bool(x)" or "x" or "not x" 

72 # http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=True/False_evaluations#True/False_evaluations # noqa 

73 return not x and x is not None