Morph

Decorators

This section explains the decorators provided by morphdb-utils. Decorators are a Python syntax for adding specific functionalities, allowing you to write complex processes in simple code. morphdb-utils provides decorators for data transformation, visualization, report creation, and API calls out of the box.


Types of Decorators

@transform

Applies to functions to perform data transformation. Functions with this decorator must return a Pandas DataFrame.

from typing import Dict
import pandas as pd
from morphdb_utils.annotations import transform

example = {
    "Name": ["John Doe", "Jane Smith", "Emily Zhang"],
    "Age": [28, 34, 22],
    "Occupation": ["Software Engineer", "Data Scientist", "Marketing Manager"],
}

data: Dict[str, pd.DataFrame] = {
    "example": pd.DataFrame(example)
}

@transform
def main(data: Dict[str, pd.DataFrame]) -> pd.DataFrame:
    df = data["example"]
    df["Age in 5 Years"] = df["Age"] + 5
    return df

@visualize

Applies to functions to create visualizations. Graphs are made using the matplotlib or plotly libraries and returns the results in HTML or PNG format.

from typing import Dict
import pandas as pd
import matplotlib.pyplot as plt
from morphdb_utils.annotations import visualize

example = {
    "Name": ["John Doe", "Jane Smith", "Emily Zhang"],
    "Age": [28, 34, 22],
    "Occupation": ["Software Engineer", "Data Scientist", "Marketing Manager"],
}

data: Dict[str, pd.DataFrame] = {
    "example": pd.DataFrame(example)
}

@visualize(library="matplotlib")
def main(data: Dict[str, pd.DataFrame]) -> pd.DataFrame:
    df = data["example"]
    fig, ax = plt.subplots()
    df.plot(kind='bar', x='Name', y='Age', ax=ax)
    ax.set_title("Age of Individuals")
    ax.set_xlabel("Name")
    ax.set_ylabel("Age")
    return fig

@report

Applies to functions to generate a report in Markdown format.

from typing import Dict
from morphdb_utils.annotations import report
import pandas as pd

example = {
    "Name": ["John Doe", "Jane Smith", "Emily Zhang"],
    "Age": [28, 34, 22],
    "Occupation": ["Software Engineer", "Data Scientist", "Marketing Manager"],
}

data: Dict[str, pd.DataFrame] = {
    "example": pd.DataFrame(example)
}

@report
def main(data: Dict[str, pd.DataFrame]) -> str:
    df = data["example"]
    report = "# Individual report\n\n"
    report += df.to_csv(index=False)  # CSV形式で代用
    return report

@api

Applies to functions to perform API calls, returning a JSON.

from typing import Dict
from morphdb_utils.annotations import api
import pandas as pd

example = {
    "Name": ["John Doe", "Jane Smith", "Emily Zhang"],
    "Age": [28, 34, 22],
    "Occupation": ["Software Engineer", "Data Scientist", "Marketing Manager"],
}

data: Dict[str, pd.DataFrame] = {
    "example": pd.DataFrame(example)
}

@api
def main(data: Dict[str, pd.DataFrame]) -> dict:
    df = data["example"]
    tables_list = df["Name"].tolist()
    return {"tables": tables_list}