namedtuple1.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. try:
  2. try:
  3. from ucollections import namedtuple
  4. except ImportError:
  5. from collections import namedtuple
  6. except ImportError:
  7. print("SKIP")
  8. raise SystemExit
  9. T = namedtuple("Tup", ["foo", "bar"])
  10. # CPython prints fully qualified name, what we don't bother to do so far
  11. #print(T)
  12. for t in T(1, 2), T(bar=1, foo=2):
  13. print(t)
  14. print(t[0], t[1])
  15. print(t.foo, t.bar)
  16. print(len(t))
  17. print(bool(t))
  18. print(t + t)
  19. print(t * 3)
  20. print([f for f in t])
  21. print(isinstance(t, tuple))
  22. # Create using positional and keyword args
  23. print(T(3, bar=4))
  24. try:
  25. t[0] = 200
  26. except TypeError:
  27. print("TypeError")
  28. try:
  29. t.bar = 200
  30. except AttributeError:
  31. print("AttributeError")
  32. try:
  33. t = T(1)
  34. except TypeError:
  35. print("TypeError")
  36. try:
  37. t = T(1, 2, 3)
  38. except TypeError:
  39. print("TypeError")
  40. try:
  41. t = T(foo=1)
  42. except TypeError:
  43. print("TypeError")
  44. try:
  45. t = T(1, foo=1)
  46. except TypeError:
  47. print("TypeError")
  48. # enough args, but kw is wrong
  49. try:
  50. t = T(1, baz=3)
  51. except TypeError:
  52. print("TypeError")
  53. # bad argument for member spec
  54. try:
  55. namedtuple('T', 1)
  56. except TypeError:
  57. print("TypeError")
  58. # Try single string
  59. T3 = namedtuple("TupComma", "foo bar")
  60. t = T3(1, 2)
  61. print(t.foo, t.bar)
  62. # Try tuple
  63. T4 = namedtuple("TupTuple", ("foo", "bar"))
  64. t = T4(1, 2)
  65. print(t.foo, t.bar)
  66. # Try single string with comma field separator
  67. # Not implemented so far
  68. #T2 = namedtuple("TupComma", "foo,bar")
  69. #t = T2(1, 2)