fork download
  1. '''
  2. Conflicting method names in python
  3. '''
  4.  
  5. class ConflictCheck(type):
  6. def __new__(meta, name, bases, dct):
  7. # determine attributes per base class, except for magic ones
  8. attrs_per_base = [set(a for a in dir(b) if not a.startswith("__"))
  9. for b in bases]
  10. if len(set.union(*attrs_per_base)) < sum(map(len, attrs_per_base)):
  11. raise ValueError("attribute conflict")
  12. return super(ConflictCheck, meta).__new__(meta, name, bases, dct)
  13.  
  14. class Tiger():
  15. @staticmethod
  16. def speak():
  17. print "Rawr!";
  18.  
  19. class Lion():
  20. @staticmethod
  21. def speak():
  22. print "Roar!";
  23.  
  24. class Liger(Lion, Tiger):
  25. __metaclass__ = ConflictCheck # will raise an error at definition time
  26.  
  27. Liger.speak(); ''' this prints "Rawr" instead of printing an error message. '''
  28. '''Is there any way to detect method name collisions like this one?'''
Runtime error #stdin #stdout 0.01s 7724KB
stdin
Standard input is empty
stdout
Standard output is empty