Extend Python tuple Subclass Returned by Function namedtuple

Attempt to extend a subclass returned from namedtuple.

In [1]:
from collections import namedtuple
import itertools as it
In [2]:
from chamelboots import VALID_STATEMENTS, ChameleonTemplate, TalStatement

from chamelboots.constants import Join
In [3]:
type(namedtuple)
Out[3]:
function
In [4]:
TalStatement = namedtuple("TalStatement", "name value")
In [5]:
type(TalStatement)
Out[5]:
type
In [6]:
VALID_STATEMENTS
Out[6]:
{'tal:define': 'define',
 'tal:switch': 'switch',
 'tal:condition': 'condition',
 'tal:repeat': 'repeat',
 'tal:case': 'case',
 'tal:content': 'content',
 'tal:replace': 'replace',
 'tal:omit-tag': 'omit-tag',
 'tal:attributes': 'attributes',
 'tal:on-error': 'on-error'}
In [21]:
class SelfVerifyingTalStatement(TalStatement):
    """Define a tuple that verifies its values."""

    def __init__(self, name, value):
        """Verify before init of parent."""
        valid_statements = VALID_STATEMENTS

        for message, condition in (
            (
                f'"{name}" must be one of the following: {Join.COMMASPACE(valid_statements.values())}',
                name not in valid_statements,
            ),
            (f'"{value}" cannot be in the value.', name in value.strip().lower(),),
        ):
            if condition:
                raise ValueError(message)
        super().__init__()
In [22]:
for args in (
    ("spam", "eggs"),
    *zip(VALID_STATEMENTS, (f" {key.upper()} " for key in VALID_STATEMENTS),),
    ("attributes", "attrib",),
):
    try:
        print(SelfVerifyingTalStatement(*args))
    except ValueError as err:
        print(dict(args=args))
        print(err)
print("passes")
{'args': ('spam', 'eggs')}
"spam" must be one of the following: define, switch, condition, repeat, case, content, replace, omit-tag, attributes, on-error
{'args': ('tal:define', ' TAL:DEFINE ')}
" TAL:DEFINE " cannot be in the value.
{'args': ('tal:switch', ' TAL:SWITCH ')}
" TAL:SWITCH " cannot be in the value.
{'args': ('tal:condition', ' TAL:CONDITION ')}
" TAL:CONDITION " cannot be in the value.
{'args': ('tal:repeat', ' TAL:REPEAT ')}
" TAL:REPEAT " cannot be in the value.
{'args': ('tal:case', ' TAL:CASE ')}
" TAL:CASE " cannot be in the value.
{'args': ('tal:content', ' TAL:CONTENT ')}
" TAL:CONTENT " cannot be in the value.
{'args': ('tal:replace', ' TAL:REPLACE ')}
" TAL:REPLACE " cannot be in the value.
{'args': ('tal:omit-tag', ' TAL:OMIT-TAG ')}
" TAL:OMIT-TAG " cannot be in the value.
{'args': ('tal:attributes', ' TAL:ATTRIBUTES ')}
" TAL:ATTRIBUTES " cannot be in the value.
{'args': ('tal:on-error', ' TAL:ON-ERROR ')}
" TAL:ON-ERROR " cannot be in the value.
{'args': ('attributes', 'attrib')}
"attributes" must be one of the following: define, switch, condition, repeat, case, content, replace, omit-tag, attributes, on-error
passes