29 __all__ = (
"continueClass",
"inClass",
"TemplateMeta")
32 INTRINSIC_SPECIAL_ATTRIBUTES = frozenset((
46 """Return True if an attribute is safe to monkeypatch-transfer to another 49 This rejects special methods that are defined automatically for all 50 classes, leaving only those explicitly defined in a class decorated by 51 `continueClass` or registered with an instance of `TemplateMeta`. 53 if name.startswith(
"__")
and (value
is getattr(object, name,
None)
or 54 name
in INTRINSIC_SPECIAL_ATTRIBUTES):
60 """Re-open the decorated class, adding any new definitions into the original. 64 .. code-block:: python 76 .. code-block:: python 83 orig = getattr(sys.modules[cls.__module__], cls.__name__)
90 attr = cls.__dict__.get(name,
None)
or getattr(cls, name)
92 setattr(orig, name, attr)
97 """Add the decorated function to the given class as a method. 101 .. code-block:: python 112 .. code-block:: python 118 Standard decorators like ``classmethod``, ``staticmethod``, and 119 ``property`` may be used *after* this decorator. Custom decorators 120 may only be used if they return an object with a ``__name__`` attribute 121 or the ``name`` optional argument is provided. 128 if hasattr(func,
"__name__"):
129 name1 = func.__name__
131 if hasattr(func,
"__func__"):
133 name1 = func.__func__.__name__
134 elif hasattr(func,
"fget"):
136 name1 = func.fget.__name__
139 "Could not guess attribute name for '{}'.".
format(func)
141 setattr(cls, name1, func)
147 """A metaclass for abstract base classes that tie together wrapped C++ 150 C++ template classes are most easily wrapped with a separate Python class 151 for each template type, which results in an unnatural Python interface. 152 TemplateMeta provides a thin layer that connects these Python classes by 153 giving them a common base class and acting as a factory to construct them 156 To use, simply create a new class with the name of the template class, and 157 use ``TemplateMeta`` as its metaclass, and then call ``register`` on each 158 of its subclasses. This registers the class with a "type key" - usually a 159 Python representation of the C++ template types. The type key must be a 160 hashable object - strings, type objects, and tuples of these (for C++ 161 classes with multiple template parameters) are good choices. Alternate 162 type keys for existing classes can be added by calling ``alias``, but only 163 after a subclass already been registered with a "primary" type key. For 164 example (using Python 3 metaclass syntax):: 166 .. code-block:: python 169 from ._image import ImageF, ImageD 171 class Image(metaclass=TemplateMeta): 174 Image.register(np.float32, ImageF) 175 Image.register(np.float64, ImageD) 176 Image.alias("F", ImageF) 177 Image.alias("D", ImageD) 179 We have intentionally used ``numpy`` types as the primary keys for these 180 objects in this example, with strings as secondary aliases simply because 181 the primary key is added as a ``dtype`` attribute on the the registered 182 classes (so ``ImageF.dtype == numpy.float32`` in the above example). 184 This allows user code to construct objects directly using ``Image``, as 185 long as an extra ``dtype`` keyword argument is passed that matches one of 188 .. code-block:: python 190 img = Image(52, 64, dtype=np.float32) 192 This simply forwards additional positional and keyword arguments to the 193 wrapped template class's constructor. 195 The choice of "dtype" as the name of the template parameter is also 196 configurable, and in fact multiple template parameters are also supported, 197 by setting a ``TEMPLATE_PARAMS`` class attribute on the ABC to a tuple 198 containing the names of the template parameters. A ``TEMPLATE_DEFAULTS`` 199 attribute can also be defined to a tuple of the same length containing 200 default values for the template parameters, allowing them to be omitted in 201 constructor calls. When the length of these attributes is more than one, 202 the type keys passed to ``register`` and ``alias`` should be tuple of the 203 same length; when the length of these attributes is one, type keys should 204 generally not be tuples. 206 As an aid for those writing the Python wrappers for C++ classes, 207 ``TemplateMeta`` also provides a way to add pure-Python methods and other 208 attributes to the wrapped template classes. To add a ``sum`` method to 209 all registered types, for example, we can just do:: 211 .. code-block:: python 213 class Image(metaclass=TemplateMeta): 216 return np.sum(self.getArray()) 218 Image.register(np.float32, ImageF) 219 Image.register(np.float64, ImageD) 223 ``TemplateMeta`` works by overriding the ``__instancecheck__`` and 224 ``__subclasscheck__`` special methods, and hence does not appear in 225 its registered subclasses' method resolution order or ``__bases__`` 226 attributes. That means its attributes are not inherited by registered 227 subclasses. Instead, attributes added to an instance of 228 ``TemplateMeta`` are *copied* into the types registered with it. These 229 attributes will thus *replace* existing attributes in those classes 230 with the same name, and subclasses cannot delegate to base class 231 implementations of these methods. 233 Finally, abstract base classes that use ``TemplateMeta`` define a dict- 234 like interface for accessing their registered subclasses, providing 235 something like the C++ syntax for templates:: 237 .. code-block:: python 239 Image[np.float32] -> ImageF 242 Both primary dtypes and aliases can be used as keys in this interface, 243 which means types with aliases will be present multiple times in the dict. 244 To obtain the sequence of unique subclasses, use the ``__subclasses__`` 254 attrs[
"_inherited"] = {k: v
for k, v
in attrs.items()
262 attrs[
"TEMPLATE_PARAMS"] = \
263 attrs[
"_inherited"].pop(
"TEMPLATE_PARAMS", (
"dtype",))
264 attrs[
"TEMPLATE_DEFAULTS"] = \
265 attrs[
"_inherited"].pop(
"TEMPLATE_DEFAULTS",
266 (
None,)*len(attrs[
"TEMPLATE_PARAMS"]))
267 attrs[
"_registry"] = dict()
268 self = type.__new__(cls, name, bases, attrs)
270 if len(self.TEMPLATE_PARAMS) == 0:
272 "TEMPLATE_PARAMS must be a tuple with at least one element." 274 if len(self.TEMPLATE_DEFAULTS) != len(self.TEMPLATE_PARAMS):
276 "TEMPLATE_PARAMS and TEMPLATE_DEFAULTS must have same length." 290 for p, d
in zip(self.TEMPLATE_PARAMS, self.TEMPLATE_DEFAULTS):
291 tempKey = kwds.pop(p, d)
292 if isinstance(tempKey, np.dtype):
293 tempKey = tempKey.type
298 cls = self._registry.
get(key[0]
if len(key) == 1
else key,
None)
300 d = {k: v
for k, v
in zip(self.TEMPLATE_PARAMS, key)}
301 raise TypeError(
"No registered subclass for {}.".
format(d))
302 return cls(*args, **kwds)
307 if subclass
in self._registry:
309 for v
in self._registry.
values():
310 if issubclass(subclass, v):
317 if type(instance)
in self._registry:
319 for v
in self._registry.
values():
320 if isinstance(instance, v):
325 """Return a tuple of all classes that inherit from this class. 330 return tuple(
set(self._registry.
values()))
333 """Register a subclass of this ABC with the given key (a string, 334 number, type, or other hashable). 336 Register may only be called once for a given key or a given subclass. 339 raise ValueError(
"None may not be used as a key.")
340 if subclass
in self._registry.
values():
342 "This subclass has already registered with another key; " 343 "use alias() instead." 345 if self._registry.setdefault(key, subclass) != subclass:
346 if len(self.TEMPLATE_PARAMS) == 1:
347 d = {self.TEMPLATE_PARAMS[0]: key}
349 d = {k: v
for k, v
in zip(self.TEMPLATE_PARAMS, key)}
351 "Another subclass is already registered with {}".
format(d)
355 if self.TEMPLATE_DEFAULTS:
356 defaults = (self.TEMPLATE_DEFAULTS[0]
if 357 len(self.TEMPLATE_DEFAULTS) == 1
else 358 self.TEMPLATE_DEFAULTS)
360 conflictStr = (
"Base Class has an attribute with the same" 361 "name as a {} method in the default subclass" 362 ". Cannot link {} method to base class")
371 for name
in subclass.__dict__:
372 if name ==
"__new__":
374 obj = subclass.__dict__[name]
376 isBuiltin = isinstance(obj, types.BuiltinFunctionType)
377 isStatic = isinstance(obj, staticmethod)
378 if isBuiltin
or isStatic:
379 if hasattr(self, name):
380 raise AttributeError(conflictStr.format(
"static"))
381 setattr(self, name, obj)
383 elif isinstance(obj, classmethod):
384 if hasattr(self, name):
385 raise AttributeError(conflictStr.format(
"class"))
386 setattr(self, name, getattr(subclass, name))
388 def setattrSafe(name, value):
390 currentValue = getattr(subclass, name)
391 if currentValue != value:
392 msg = (
"subclass already has a '{}' attribute with " 395 msg.format(name, currentValue, value)
397 except AttributeError:
398 setattr(subclass, name, value)
400 if len(self.TEMPLATE_PARAMS) == 1:
401 setattrSafe(self.TEMPLATE_PARAMS[0], key)
402 elif len(self.TEMPLATE_PARAMS) == len(key):
403 for p, k
in zip(self.TEMPLATE_PARAMS, key):
407 "key must have {} elements (one for each of {})".
format(
408 len(self.TEMPLATE_PARAMS), self.TEMPLATE_PARAMS
412 for name, attr
in self._inherited.
items():
413 setattr(subclass, name, attr)
416 """Add an alias that allows an existing subclass to be accessed with a 420 raise ValueError(
"None may not be used as a key.")
421 if key
in self._registry:
422 raise KeyError(
"Cannot multiply-register key {}".
format(key))
423 primaryKey = tuple(getattr(subclass, p,
None)
424 for p
in self.TEMPLATE_PARAMS)
425 if len(primaryKey) == 1:
427 primaryKey = primaryKey[0]
428 if self._registry.
get(primaryKey,
None) != subclass:
429 raise ValueError(
"Subclass is not registered with this base class.")
430 self._registry[key] = subclass
436 return self._registry[key]
439 return iter(self._registry)
442 return len(self._registry)
445 return key
in self._registry
448 """Return an iterable containing all keys (including aliases). 450 return self._registry.
keys()
453 """Return an iterable of registered subclasses, with duplicates 454 corresponding to any aliases. 456 return self._registry.
values()
459 """Return an iterable of (key, subclass) pairs. 461 return self._registry.
items()
463 def get(self, key, default=None):
464 """Return the subclass associated with the given key (including 465 aliases), or ``default`` if the key is not recognized. 467 return self._registry.
get(key, default)
def isAttributeSafeToTransfer(name, value)
daf::base::PropertySet * set
def format(config, name=None, writeSourceLine=True, prefix="", verbose=False)
def inClass(cls, name=None)