case class in python

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

case class in python
Class notation in Python
Landmines hidden in Python class variables
Read PNG chunks in Python (class)
Examine the object's class in python
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
[Python] class, instance
SendKeys in Python
"Kanrika" python class
Meta-analysis in Python
Unittest in python
About python, class
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Python class, instance
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
#Python basics (class)
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Generate a first class collection in Python
[Introduction to Python] How to use class in Python?
Implement __eq__ etc. generically in Python class
Playing card class in Python (with comparison)
How to use __slots__ in Python class
Generate a class from a string in Python
Sorted list in Python
Daily AtCoder # 36 in Python
Clustering text in Python