run-python38.test 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. -- Test cases for Python 3.8 features
  2. [case testWalrus1]
  3. from typing import Optional
  4. def foo(x: int) -> Optional[int]:
  5. if x < 0:
  6. return None
  7. return x
  8. def test(x: int) -> str:
  9. if (n := foo(x)) is not None:
  10. return str(x)
  11. else:
  12. return "<fail>"
  13. [file driver.py]
  14. from native import test
  15. assert test(10) == "10"
  16. assert test(-1) == "<fail>"
  17. [case testWalrus2]
  18. from typing import Optional, Tuple, List
  19. class Node:
  20. def __init__(self, val: int, next: Optional['Node']) -> None:
  21. self.val = val
  22. self.next = next
  23. def pairs(nobe: Optional[Node]) -> List[Tuple[int, int]]:
  24. if nobe is None:
  25. return []
  26. l = []
  27. while next := nobe.next:
  28. l.append((nobe.val, next.val))
  29. nobe = next
  30. return l
  31. def make(l: List[int]) -> Optional[Node]:
  32. cur: Optional[Node] = None
  33. for x in reversed(l):
  34. cur = Node(x, cur)
  35. return cur
  36. [file driver.py]
  37. from native import Node, make, pairs
  38. assert pairs(make([1,2,3])) == [(1,2), (2,3)]
  39. assert pairs(make([1])) == []
  40. assert pairs(make([])) == []
  41. [case testFStrings]
  42. from datetime import datetime
  43. def test_fstring_equal_sign() -> None:
  44. today = datetime(year=2017, month=1, day=27)
  45. assert f"{today=:%B %d, %Y}" == 'today=January 27, 2017' # using date format specifier and debugging
  46. foo = "bar"
  47. assert f"{ foo = }" == " foo = 'bar'" # preserves whitespace
  48. line = "The mill's closed"
  49. assert f"{line = }" == 'line = "The mill\'s closed"'
  50. assert f"{line = :20}" == "line = The mill's closed "
  51. assert f"{line = !r:20}" == 'line = "The mill\'s closed" '
  52. [case testMethodOverrideDefaultPosOnly1]
  53. class Foo:
  54. def f(self, x: int=20, /, *, z: int=10) -> None:
  55. pass
  56. class Bar(Foo):
  57. def f(self, *args: int, **kwargs: int) -> None:
  58. print("stuff", args, kwargs)
  59. z: Foo = Bar()
  60. z.f(1, z=50)
  61. z.f()
  62. z.f(1)
  63. z.f(z=50)
  64. [out]
  65. stuff (1,) {'z': 50}
  66. stuff () {}
  67. stuff (1,) {}
  68. stuff () {'z': 50}