File: factory_helper.py

package info (click to toggle)
python-enaml 0.19.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,284 kB
  • sloc: python: 31,443; cpp: 4,499; makefile: 140; javascript: 68; lisp: 53; sh: 20
file content (63 lines) | stat: -rw-r--r-- 2,069 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#------------------------------------------------------------------------------
# Copyright (c) 2014-2024,, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
#------------------------------------------------------------------------------
from atom.api import Callable, Tuple, Dict

from .constraint_helper import ConstraintHelper


class FactoryHelper(ConstraintHelper):
    """ A constraint helper which delegates to a factory callable.

    """
    #: The callable object which will generate the list of constraints.
    #: It will be passed the constraints widget owner as the first
    #: argument, and should return the list of generated constraints.
    factory = Callable()

    #: Additional positional arguments to pass to the callable.
    args = Tuple()

    #: Additional keyword arguments to pass to the callable.
    kwargs = Dict()

    def __init__(self, factory, *args, **kwargs):
        """ Initialize a FactoryHelper.

        Parameters
        ----------
        factory : callable
            The callable object which generates the constraints.

        *args
            Additional positional arguments to pass to the factory.

        **kwargs
            Additional keyword arguments to pass to the factory.

        """
        self.factory = factory
        self.args = args
        self.kwargs = kwargs

    def constraints(self, component):
        """ Generate the constraints using the underlying factory.

        This method will automatically expand ConstraintHelper objects
        which are generated by the factory.

        """
        factory = self.factory
        if factory is None:
            return []
        cns = []  # inline `expand_constraints`
        for cn in factory(component, *self.args, **self.kwargs):
            if isinstance(cn, ConstraintHelper):
                cns.extend(cn.create_constraints(component))
            elif cn is not None:
                cns.append(cn)
        return cns