<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def delete_templatetype(type_id,template_i=None, **kwargs):
 """ Delete a template type and its typeattrs. """

    try:
        tmpltype_i = db.DBSession.query(TemplateType).filter(TemplateType.id == type_id).one()
    except NoResultFound:
        raise ResourceNotFoundError("Template Type %s not found"%(type_id,))

    if template_i is None:
        template_i = db.DBSession.query(Template).filter(Template.id==tmpltype_i.template_id).one()

    template_i.templatetypes.remove(tmpltype_i)

    db.DBSession.delete(tmpltype_i)
    db.DBSession.flush()