PageRenderTime 152ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 0ms

/urwid/split_repr.py

https://github.com/sporkexec/urwid
Python | 149 lines | 118 code | 2 blank | 29 comment | 0 complexity | a678bbe8d04365a5dd7f588d87af83d2 MD5 | raw file
  1. #!/usr/bin/python
  2. #
  3. # Urwid split_repr helper functions
  4. # Copyright (C) 2004-2011 Ian Ward
  5. #
  6. # This library is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU Lesser General Public
  8. # License as published by the Free Software Foundation; either
  9. # version 2.1 of the License, or (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. # Lesser General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public
  17. # License along with this library; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19. #
  20. # Urwid web site: http://excess.org/urwid/
  21. from inspect import getargspec
  22. from urwid.compat import PYTHON3, bytes
  23. def split_repr(self):
  24. """
  25. Return a helpful description of the object using
  26. self._repr_words() and self._repr_attrs() to add
  27. to the description. This function may be used by
  28. adding code to your class like this:
  29. >>> class Foo(object):
  30. ... __repr__ = split_repr
  31. ... def _repr_words(self):
  32. ... return ["words", "here"]
  33. ... def _repr_attrs(self):
  34. ... return {'attrs': "appear too"}
  35. >>> Foo()
  36. <Foo words here attrs='appear too'>
  37. >>> class Bar(Foo):
  38. ... def _repr_words(self):
  39. ... return Foo._repr_words(self) + ["too"]
  40. ... def _repr_attrs(self):
  41. ... return dict(Foo._repr_attrs(self), barttr=42)
  42. >>> Bar()
  43. <Bar words here too attrs='appear too' barttr=42>
  44. """
  45. alist = [(str(k), normalize_repr(v))
  46. for k, v in self._repr_attrs().items()]
  47. alist.sort()
  48. words = self._repr_words()
  49. if not words and not alist:
  50. # if we're just going to print the classname fall back
  51. # to the previous __repr__ implementation instead
  52. return super(self.__class__, self).__repr__()
  53. if words and alist: words.append("")
  54. return "<%s %s>" % (self.__class__.__name__,
  55. " ".join(words) +
  56. " ".join(["%s=%s" % itm for itm in alist]))
  57. def normalize_repr(v):
  58. """
  59. Return dictionary repr sorted by keys, leave others unchanged
  60. >>> normalize_repr({1:2,3:4,5:6,7:8})
  61. '{1: 2, 3: 4, 5: 6, 7: 8}'
  62. >>> normalize_repr('foo')
  63. "'foo'"
  64. """
  65. if isinstance(v, dict):
  66. items = [(repr(k), repr(v)) for k, v in v.items()]
  67. items.sort()
  68. return "{" + ", ".join([
  69. "%s: %s" % itm for itm in items]) + "}"
  70. return repr(v)
  71. def python3_repr(v):
  72. """
  73. Return strings and byte strings as they appear in Python 3
  74. >>> python3_repr(u"text")
  75. "'text'"
  76. >>> python3_repr(bytes())
  77. "b''"
  78. """
  79. r = repr(v)
  80. if not PYTHON3:
  81. if isinstance(v, bytes):
  82. return 'b' + r
  83. if r.startswith('u'):
  84. return r[1:]
  85. return r
  86. def remove_defaults(d, fn):
  87. """
  88. Remove keys in d that are set to the default values from
  89. fn. This method is used to unclutter the _repr_attrs()
  90. return value.
  91. d will be modified by this function.
  92. Returns d.
  93. >>> class Foo(object):
  94. ... def __init__(self, a=1, b=2):
  95. ... self.values = a, b
  96. ... __repr__ = split_repr
  97. ... def _repr_words(self):
  98. ... return ["object"]
  99. ... def _repr_attrs(self):
  100. ... d = dict(a=self.values[0], b=self.values[1])
  101. ... return remove_defaults(d, Foo.__init__)
  102. >>> Foo(42, 100)
  103. <Foo object a=42 b=100>
  104. >>> Foo(10, 2)
  105. <Foo object a=10>
  106. >>> Foo()
  107. <Foo object>
  108. """
  109. args, varargs, varkw, defaults = getargspec(fn)
  110. # ignore *varargs and **kwargs
  111. if varkw:
  112. del args[-1]
  113. if varargs:
  114. del args[-1]
  115. # create adictionary of args with default values
  116. ddict = dict(zip(args[len(args) - len(defaults):], defaults))
  117. for k, v in d.items():
  118. if k in ddict:
  119. # remove values that match their defaults
  120. if ddict[k] == v:
  121. del d[k]
  122. return d
  123. def _test():
  124. import doctest
  125. doctest.testmod()
  126. if __name__=='__main__':
  127. _test()