|
| 1 | +# cmd2 Mixin Template |
| 2 | + |
| 3 | +## Mixin Classes in General |
| 4 | + |
| 5 | +In Python, a mixin is a class designed to provide a specific set of functionalities to other classes |
| 6 | +through multiple inheritance. Mixins are not intended to be instantiated on their own; rather, they |
| 7 | +serve as a way to "mix in" or compose behaviors into a base class without creating a rigid "is-a" |
| 8 | +relationship. |
| 9 | + |
| 10 | +For more information about Mixin Classes, we recommend this `Real Python` article on |
| 11 | +[What Are Mixin Classes in Python?](https://realpython.com/python-mixin/). |
| 12 | + |
| 13 | +## Overview of cmd2 mixins |
| 14 | + |
| 15 | +If you have some set of re-usable behaviors that you wish to apply to multiple different `cmd2` |
| 16 | +applications, then creating a mixin class to encapsulate this behavior can be a great idea. It is |
| 17 | +one way to extend `cmd2` by relying on multiple inheritance. It is quick and easy, but there are |
| 18 | +some potential pitfalls you should be aware of so you know how to do it correctly. |
| 19 | + |
| 20 | +The [mixins.py](https://github.com/python-cmd2/cmd2/blob/main/examples/mixins.py) example is a |
| 21 | +general example that shows you how you can develop a mixin class for `cmd2` applicaitons. In the |
| 22 | +past we have referred to these as "Plugins", but in retrospect that probably isn't the best name for |
| 23 | +them. They are generally mixin classes that add some extra functionality to your class which |
| 24 | +inherits from [cmd2.Cmd][]. |
| 25 | + |
| 26 | +## Using this template |
| 27 | + |
| 28 | +This file provides a very basic template for how you can create your own cmd2 Mixin class to |
| 29 | +encapsulate re-usable behavior that can be applied to multiple `cmd2` applications via multiple |
| 30 | +inheritance. |
| 31 | + |
| 32 | +## Naming |
| 33 | + |
| 34 | +If you decide to publish your Mixin as a Python package, you should consider prefixing the name of |
| 35 | +your project with `cmd2-`. If you take this approach, then within that project, you should have a |
| 36 | +package with a prefix of `cmd2_`. |
| 37 | + |
| 38 | +## Adding functionality |
| 39 | + |
| 40 | +There are many ways to add functionality to `cmd2` using a mixin. A mixin is a class that |
| 41 | +encapsulates and injects code into another class. Developers who use a mixin in their `cmd2` |
| 42 | +project, will inject the mixin's code into their subclass of [cmd2.Cmd][]. |
| 43 | + |
| 44 | +### Mixin and Initialization |
| 45 | + |
| 46 | +The following short example shows how to create a mixin class and how everything gets initialized. |
| 47 | + |
| 48 | +Here's the mixin: |
| 49 | + |
| 50 | +```python |
| 51 | +class MyMixin: |
| 52 | + def __init__(self, *args, **kwargs): |
| 53 | + # code placed here runs before cmd2.Cmd initializes |
| 54 | + super().__init__(*args, **kwargs) |
| 55 | + # code placed here runs after cmd2.Cmd initializes |
| 56 | +``` |
| 57 | + |
| 58 | +and an example app which uses the mixin: |
| 59 | + |
| 60 | +```python |
| 61 | +import cmd2 |
| 62 | + |
| 63 | + |
| 64 | +class Example(MyMixin, cmd2.Cmd): |
| 65 | + """A cmd2 application class to show how to use a mixin class.""" |
| 66 | + |
| 67 | + def __init__(self, *args, **kwargs): |
| 68 | + # code placed here runs before cmd2.Cmd or |
| 69 | + # any mixins initialize |
| 70 | + super().__init__(*args, **kwargs) |
| 71 | + # code placed here runs after cmd2.Cmd and |
| 72 | + # all mixins have initialized |
| 73 | +``` |
| 74 | + |
| 75 | +Note how the mixin must be inherited (or mixed in) before `cmd2.Cmd`. This is required for two |
| 76 | +reasons: |
| 77 | + |
| 78 | +- The `cmd.Cmd.__init__()` method in the python standard library does not call `super().__init__()`. |
| 79 | + Because of this oversight, if you don't inherit from `MyMixin` first, the `MyMixin.__init__()` |
| 80 | + method will never be called. |
| 81 | +- You may want your mixin to be able to override methods from `cmd2.Cmd`. If you mixin the mixin |
| 82 | + class after `cmd2.Cmd`, the python method resolution order will call `cmd2.Cmd` methods before it |
| 83 | + calls those in your mixin. |
| 84 | + |
| 85 | +### Add commands |
| 86 | + |
| 87 | +Your mixin can add user visible commands. You do it the same way in a mixin that you would in a |
| 88 | +`cmd2.Cmd` app: |
| 89 | + |
| 90 | +```python |
| 91 | +class MyMixin: |
| 92 | + |
| 93 | + def do_say(self, statement): |
| 94 | + """Simple say command""" |
| 95 | + self.poutput(statement) |
| 96 | +``` |
| 97 | + |
| 98 | +You have all the same capabilities within the mixin that you do inside a `cmd2.Cmd` app, including |
| 99 | +argument parsing via decorators and custom help methods. |
| 100 | + |
| 101 | +### Add (or hide) settings |
| 102 | + |
| 103 | +A mixin may add user controllable settings to the application. Here's an example: |
| 104 | + |
| 105 | +```python |
| 106 | +class MyMixin: |
| 107 | + def __init__(self, *args, **kwargs): |
| 108 | + # code placed here runs before cmd2.Cmd initializes |
| 109 | + super().__init__(*args, **kwargs) |
| 110 | + # code placed here runs after cmd2.Cmd initializes |
| 111 | + self.mysetting = 'somevalue' |
| 112 | + self.settable.update({'mysetting': 'short help message for mysetting'}) |
| 113 | +``` |
| 114 | + |
| 115 | +You can also hide settings from the user by removing them from `self.settable`. |
| 116 | + |
| 117 | +### Decorators |
| 118 | + |
| 119 | +Your mixin can provide a decorator which users of your mixin can use to wrap functionality around |
| 120 | +their own commands. |
| 121 | + |
| 122 | +### Override methods |
| 123 | + |
| 124 | +Your mixin can override core `cmd2.Cmd` methods, changing their behavior. This approach should be |
| 125 | +used sparingly, because it is very brittle. If a developer chooses to use multiple mixins in their |
| 126 | +application, and several of the mixins override the same method, only the first mixin to be mixed in |
| 127 | +will have the overridden method called. |
| 128 | + |
| 129 | +Hooks are a much better approach. |
| 130 | + |
| 131 | +### Hooks |
| 132 | + |
| 133 | +Mixins can register hooks, which are called by `cmd2.Cmd` during various points in the application |
| 134 | +and command processing lifecycle. Mixins should not override any of the legacy `cmd` hook methods, |
| 135 | +instead they should register their hooks as |
| 136 | +[described](https://cmd2.readthedocs.io/en/latest/hooks.html) in the `cmd2` documentation. |
| 137 | + |
| 138 | +You should name your hooks so that they begin with the name of your mixin. Hook methods get mixed |
| 139 | +into the `cmd2` application and this naming convention helps avoid unintentional method overriding. |
| 140 | + |
| 141 | +Here's a simple example: |
| 142 | + |
| 143 | +```python |
| 144 | +class MyMixin: |
| 145 | + |
| 146 | + def __init__(self, *args, **kwargs): |
| 147 | + # code placed here runs before cmd2 initializes |
| 148 | + super().__init__(*args, **kwargs) |
| 149 | + # code placed here runs after cmd2 initializes |
| 150 | + # this is where you register any hook functions |
| 151 | + self.register_postparsing_hook(self.cmd2_mymixin_postparsing_hook) |
| 152 | + |
| 153 | + def cmd2_mymixin_postparsing_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData: |
| 154 | + """Method to be called after parsing user input, but before running the command""" |
| 155 | + self.poutput('in postparsing_hook') |
| 156 | + return data |
| 157 | +``` |
| 158 | + |
| 159 | +Registration allows multiple mixins (or even the application itself) to each inject code to be |
| 160 | +called during the application or command processing lifecycle. |
| 161 | + |
| 162 | +See the [cmd2 hook documentation](https://cmd2.readthedocs.io/en/latest/hooks.html) for full details |
| 163 | +of the application and command lifecycle, including all available hooks and the ways hooks can |
| 164 | +influence the lifecycle. |
| 165 | + |
| 166 | +### Classes and Functions |
| 167 | + |
| 168 | +Your mixin can also provide classes and functions which can be used by developers of `cmd2` based |
| 169 | +applications. Describe these classes and functions in your documentation so users of your mixin will |
| 170 | +know what's available. |
0 commit comments