home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / lib / python2.6 / abc.py < prev    next >
Encoding:
Python Source  |  2010-12-26  |  6.9 KB  |  183 lines

  1. # Copyright 2007 Google, Inc. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3.  
  4. """Abstract Base Classes (ABCs) according to PEP 3119."""
  5.  
  6.  
  7. # Instance of old-style class
  8. class _C: pass
  9. _InstanceType = type(_C())
  10.  
  11.  
  12. def abstractmethod(funcobj):
  13.     """A decorator indicating abstract methods.
  14.  
  15.     Requires that the metaclass is ABCMeta or derived from it.  A
  16.     class that has a metaclass derived from ABCMeta cannot be
  17.     instantiated unless all of its abstract methods are overridden.
  18.     The abstract methods can be called using any of the normal
  19.     'super' call mechanisms.
  20.  
  21.     Usage:
  22.  
  23.         class C:
  24.             __metaclass__ = ABCMeta
  25.             @abstractmethod
  26.             def my_abstract_method(self, ...):
  27.                 ...
  28.     """
  29.     funcobj.__isabstractmethod__ = True
  30.     return funcobj
  31.  
  32.  
  33. class abstractproperty(property):
  34.     """A decorator indicating abstract properties.
  35.  
  36.     Requires that the metaclass is ABCMeta or derived from it.  A
  37.     class that has a metaclass derived from ABCMeta cannot be
  38.     instantiated unless all of its abstract properties are overridden.
  39.     The abstract properties can be called using any of the normal
  40.     'super' call mechanisms.
  41.  
  42.     Usage:
  43.  
  44.         class C:
  45.             __metaclass__ = ABCMeta
  46.             @abstractproperty
  47.             def my_abstract_property(self):
  48.                 ...
  49.  
  50.     This defines a read-only property; you can also define a read-write
  51.     abstract property using the 'long' form of property declaration:
  52.  
  53.         class C:
  54.             __metaclass__ = ABCMeta
  55.             def getx(self): ...
  56.             def setx(self, value): ...
  57.             x = abstractproperty(getx, setx)
  58.     """
  59.     __isabstractmethod__ = True
  60.  
  61.  
  62. class ABCMeta(type):
  63.  
  64.     """Metaclass for defining Abstract Base Classes (ABCs).
  65.  
  66.     Use this metaclass to create an ABC.  An ABC can be subclassed
  67.     directly, and then acts as a mix-in class.  You can also register
  68.     unrelated concrete classes (even built-in classes) and unrelated
  69.     ABCs as 'virtual subclasses' -- these and their descendants will
  70.     be considered subclasses of the registering ABC by the built-in
  71.     issubclass() function, but the registering ABC won't show up in
  72.     their MRO (Method Resolution Order) nor will method
  73.     implementations defined by the registering ABC be callable (not
  74.     even via super()).
  75.  
  76.     """
  77.  
  78.     # A global counter that is incremented each time a class is
  79.     # registered as a virtual subclass of anything.  It forces the
  80.     # negative cache to be cleared before its next use.
  81.     _abc_invalidation_counter = 0
  82.  
  83.     def __new__(mcls, name, bases, namespace):
  84.         cls = super(ABCMeta, mcls).__new__(mcls, name, bases, namespace)
  85.         # Compute set of abstract method names
  86.         abstracts = set(name
  87.                      for name, value in namespace.items()
  88.                      if getattr(value, "__isabstractmethod__", False))
  89.         for base in bases:
  90.             for name in getattr(base, "__abstractmethods__", set()):
  91.                 value = getattr(cls, name, None)
  92.                 if getattr(value, "__isabstractmethod__", False):
  93.                     abstracts.add(name)
  94.         cls.__abstractmethods__ = frozenset(abstracts)
  95.         # Set up inheritance registry
  96.         cls._abc_registry = set()
  97.         cls._abc_cache = set()
  98.         cls._abc_negative_cache = set()
  99.         cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
  100.         return cls
  101.  
  102.     def register(cls, subclass):
  103.         """Register a virtual subclass of an ABC."""
  104.         if not isinstance(cls, type):
  105.             raise TypeError("Can only register classes")
  106.         if issubclass(subclass, cls):
  107.             return  # Already a subclass
  108.         # Subtle: test for cycles *after* testing for "already a subclass";
  109.         # this means we allow X.register(X) and interpret it as a no-op.
  110.         if issubclass(cls, subclass):
  111.             # This would create a cycle, which is bad for the algorithm below
  112.             raise RuntimeError("Refusing to create an inheritance cycle")
  113.         cls._abc_registry.add(subclass)
  114.         ABCMeta._abc_invalidation_counter += 1  # Invalidate negative cache
  115.  
  116.     def _dump_registry(cls, file=None):
  117.         """Debug helper to print the ABC registry."""
  118.         print >> file, "Class: %s.%s" % (cls.__module__, cls.__name__)
  119.         print >> file, "Inv.counter: %s" % ABCMeta._abc_invalidation_counter
  120.         for name in sorted(cls.__dict__.keys()):
  121.             if name.startswith("_abc_"):
  122.                 value = getattr(cls, name)
  123.                 print >> file, "%s: %r" % (name, value)
  124.  
  125.     def __instancecheck__(cls, instance):
  126.         """Override for isinstance(instance, cls)."""
  127.         # Inline the cache checking when it's simple.
  128.         subclass = getattr(instance, '__class__', None)
  129.         if subclass in cls._abc_cache:
  130.             return True
  131.         subtype = type(instance)
  132.         # Old-style instances
  133.         if subtype is _InstanceType:
  134.             subtype = subclass
  135.         if subtype is subclass or subclass is None:
  136.             if (cls._abc_negative_cache_version ==
  137.                 ABCMeta._abc_invalidation_counter and
  138.                 subtype in cls._abc_negative_cache):
  139.                 return False
  140.             # Fall back to the subclass check.
  141.             return cls.__subclasscheck__(subtype)
  142.         return (cls.__subclasscheck__(subclass) or
  143.                 cls.__subclasscheck__(subtype))
  144.  
  145.     def __subclasscheck__(cls, subclass):
  146.         """Override for issubclass(subclass, cls)."""
  147.         # Check cache
  148.         if subclass in cls._abc_cache:
  149.             return True
  150.         # Check negative cache; may have to invalidate
  151.         if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter:
  152.             # Invalidate the negative cache
  153.             cls._abc_negative_cache = set()
  154.             cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
  155.         elif subclass in cls._abc_negative_cache:
  156.             return False
  157.         # Check the subclass hook
  158.         ok = cls.__subclasshook__(subclass)
  159.         if ok is not NotImplemented:
  160.             assert isinstance(ok, bool)
  161.             if ok:
  162.                 cls._abc_cache.add(subclass)
  163.             else:
  164.                 cls._abc_negative_cache.add(subclass)
  165.             return ok
  166.         # Check if it's a direct subclass
  167.         if cls in getattr(subclass, '__mro__', ()):
  168.             cls._abc_cache.add(subclass)
  169.             return True
  170.         # Check if it's a subclass of a registered class (recursive)
  171.         for rcls in cls._abc_registry:
  172.             if issubclass(subclass, rcls):
  173.                 cls._abc_cache.add(subclass)
  174.                 return True
  175.         # Check if it's a subclass of a subclass (recursive)
  176.         for scls in cls.__subclasses__():
  177.             if issubclass(subclass, scls):
  178.                 cls._abc_cache.add(subclass)
  179.                 return True
  180.         # No dice; update negative cache
  181.         cls._abc_negative_cache.add(subclass)
  182.         return False
  183.