There is a case class in Scala. It is a guy who creates an immutable object with the argument and its name that you put in when you new.
Because it is convenient, I wanted to make something like a case class even with python, so I tried it
def caseclass(args):
    class _Case(object):
        def __init__(self, kwargs):
            self._initwargs = kwargs
        def _type_check(self, key, value):
            if isinstance(value, self._initwargs[key]) is False:
                raise TypeError;
        def init(self, **kwargs):
            [self._type_check(key, kwargs[key])  for key in kwargs]
            self._kwargs = kwargs
        def getattr(self, name):
            return self._kwargs[name]
        def setattr(self, name, value):
            raise TypeError;
    def case(klass):
        _case = _Case(args)
        krass = type(klass.__name__, klass.__bases__,
                     {
                "__getattr__":_case.getattr,
                "__setattr__":_case.setattr,
                "__init__":_case.init
                })
        return krass
    return case
So, how to use caseclass as a decorator
#{argument:argumentの型}という形式の辞書インスタンスをargumentにします
@caseclass({'foo':str, 'bar':int})
class Hoge(object):pass
hoge = Hoge(foo = "hello", bar = 1)
print(hoge.foo) # "hello"And output
print(hoge.bar) #1 and output
hoge.num = 1 #TypeError jumps when trying to set
fuga = Hoge(dosukoi = "nokotta") #And even if you specify an undefined argument, Error will fly
Maybe there is a better way
Recommended Posts