Version 2: Getting Started by Example - shiroyuki/Imagination GitHub Wiki
This is for the development version.
Prerequisite
- Python 3.4 - 3.6
- Kotoba XML Parser (kotoba 3.1)
Highlight in Version 2
- Enhancement: Simplify and streamline the setup.
- Bug: Address possible infinite recursion caused by proxy entities (Issue #24).
- Backward Incompatibility: Imagination 2 drops the support for Python 2.7 for good. If you need it, Imagination 1.30+ still supports Python 2.7.
- Enhancement: PyPy3 support is coming up soon in this major release.
Installation
Currently, you have to install via source.
git clone https://github.com/shiroyuki/Imagination.git
cd Imagination
pip3 install .
Basic Setup
Suppose your app looks like this.
root_dir/
app/
__init__.py
containers.xml
main.py
containers.xml
, which is the configuration of the framework, looks like this:
<imagination>
</imagination>
(The XML schema is still the same as Version 1.)
main.py
, which is the main script, looks like this:
from imagination.assembler.core import Assembler
assembler = Assembler()
assembler.load('containers.xml')
# TODO do something
Create a calculator
Let's create app/util.py
:
class Calculator(object):
def add(self, a:int, b:int) -> int:
return a + b
At this point, Imagination does not know about the calculator. So,
let's register a container of an instance of app.util.Calculator
in containers.xml
:
<imagination>
<entity id="calc" class="app.util.Calculator" />
</imagination>
where calc is the container ID.
Use the calculator container.
To refer the calculator container, according to main.py
, simply use
calculator = assembler.core.get('calc')
Now, to actually use the container, let's add something to the end of main.py
# Omitted the code for main.py already shown above
calculator = assembler.core.get('calc')
result = calculator.add(123, 456) # -> int(579)
print(calculator.add(123, 456)) # STDOUT: 579