Passed
Pull Request — master (#22)
by Konstantinos
02:16
created

CommandFactory.create()   A

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nop 3
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
from abc import ABC
2
import attr
3
from typing import Tuple
4
5
from so_magic.utils import Subject, Command, CommandFactoryInterface, CommandFactoryType
6
7
8
class BaseCommandFactory(metaclass=CommandFactoryType):
9
    pass
10
11
12
@BaseCommandFactory.register_as_subclass('generic')
13
class GenericCommandFactory(CommandFactoryInterface):
14
    """Command Factory that constructs a command given all the necessary arguments.
15
16
    Assumes the 1st argument is the 'receiver' (see Command module),
17
    2nd is the method to call on the receiver and the rest are the method's runtime arguments.
18
    """
19
    def construct(self, *args, **kwargs) -> Command:
20
        """Construct a command object (Command class instance).
21
22
        Assumes the 1st argument is the 'receiver' (see Command module),
23
        2nd is the method to call on the receiver and the rest are the method's runtime arguments.
24
25
        Returns:
26
            Command: the command object
27
        """
28
        return Command(*args, **kwargs)
29
30
31
@BaseCommandFactory.register_as_subclass('function')
32
class FunctionCommandFactory(CommandFactoryInterface):
33
    """Command Factory that constructs a command assuming the 1st argument is a python function.
34
35
    Assumes that the function (1st argument) acts as the the 'receiver' (see Command module),
36
    2nd is the method to call on the receiver and the rest are the method's runtime arguments.
37
    """
38
    def construct(self, *args, **kwargs) -> Command:
39
        """Construct a command object (Command class instance).
40
41
        Assumes that the 1st argument is a python function and that it acts as the the 'receiver' (see Command module).
42
        The rest are the function's runtime arguments.
43
44
        Raises:
45
            RuntimeError: [description]
46
47
        Returns:
48
            Command: [description]
49
        """
50
        if len(args) < 1:
51
            raise RuntimeError("Will break")
52
        return Command(args[0], '__call__', *args[1:])
53
54
55
class CommandFactory:
56
    """A factory class able to construct new command objects."""
57
    constructors = {k: v().construct for k, v in BaseCommandFactory.subclasses.items()}
58
59
    @classmethod
60
    def pick(cls, *args, **kwargs):
61
        decision = {True: 'function', False: 'generic'}
62
        is_function = hasattr(args[0], '__code__')
63
        dec2 = {'function': lambda x: x[0].__code__.co_name, 'generic': lambda x: type(x[0]).__name__ + '-' + x[1]}
64
        return decision[is_function], kwargs.get('name', dec2[decision[is_function]](args))
65
66
    @classmethod
67
    def create(cls, *args, **kwargs) -> Tuple[Command, str]:
68
69
        key, name = cls.pick(*args, **kwargs)
70
        if len(args) < 1:
71
            raise RuntimeError(args)
72
        return cls.constructors[key](*args), name
73
74
75
@attr.s
76
class MagicCommandFactory(Subject):
77
    """Instances of this class act as callable command factories that notify,
78
    subscribed observers/listeners upon new command object creation.
79
80
    Args:
81
        command_factory (CommandFactory, optional): an instance of a CommandFActory
82
    """
83
    command_factory = attr.ib(init=True, default=CommandFactory())
84
85
    def __call__(self, *args, **kwargs):
86
        self._state, self.name = self.command_factory.create(*args, **kwargs)
87
        self.notify()
88
        return self._state
89