Advertisement
Guest User

Untitled

a guest
May 6th, 2015
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. """Attribute Abbreviation.
  2.  
  3. This file contains a metaclass that can be used to abbreviate attribute names for a class.
  4.  
  5. This is a POC made for fun.
  6. Do yourself a favor and NEVER do this in actual code.
  7. You've been warned.
  8. """
  9.  
  10. class AbbreviationError(Exception):
  11. pass
  12.  
  13.  
  14. class Abbreviate(type):
  15. def __new__(mcs, name, bases, dict_):
  16. abbreviate = {key for key in dict_ if
  17. not key.startswith("__") and key.startswith(dict_.get("PREFIX", ""))}
  18.  
  19. if any(any(other.startswith(this) and other != this for other in abbreviate) for this in abbreviate):
  20. raise AbbreviationError("Ambiguous naming prevents proper abbreviation.")
  21.  
  22. dict_["ABBREVIATE"] = abbreviate
  23.  
  24. def __getattr__(self, name):
  25. names = [abbr for abbr in self.ABBREVIATE if abbr.startswith(self.PREFIX + name)]
  26.  
  27. if len(names) > 1:
  28. abbrev_names = [abbrev_name[len(self.PREFIX):] for abbrev_name in names]
  29. raise AttributeError("Abbreviation {!r} matches too many names: {!r}.".format(name, abbrev_names))
  30.  
  31. if not names:
  32. raise AttributeError("Abbreviation {!r} has no matches.".format(name))
  33.  
  34. return getattr(self, names[0])
  35.  
  36. dict_["__getattr__"] = __getattr__
  37.  
  38. return type.__new__(mcs, name, bases, dict_)
  39.  
  40.  
  41. class MyClass(object):
  42. __metaclass__ = Abbreviate
  43.  
  44. PREFIX = "c_"
  45.  
  46. def c_print(self, text):
  47. print text
  48.  
  49. def c_add(self, a, b):
  50. return a + b
  51.  
  52. def c_min(self, a, b):
  53. return min(a, b)
  54.  
  55. def c_max(self, a, b):
  56. return max(a, b)
  57.  
  58.  
  59. if __name__ == '__main__':
  60. my_class = MyClass()
  61.  
  62. my_class.p("Hello, Abbreviation World!") # Calls `my_class.c_print`
  63.  
  64. print my_class.a(1, 2) # Calls `my_class.add`
  65.  
  66. print my_class.min(0, 1) # Calls `my_class.min`
  67.  
  68. print my_class.c_max(1, 2) # Original method names work as well
  69.  
  70. try:
  71. print my_class.m(3, 4) # Ambiguity!
  72. except AttributeError as ex:
  73. print ex.message
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement