Is there any Python equivalent of Scala's Case Class? Like automatically generating constructors that assign to fields without writing out boilerplate.
-
What do you mean by "implementing Scala's Case Class"? Are you writing a Scala compiler in Python? What do you mean by "equivalent of Scala case class"? Which if the myriad of properties of a Scala case class do you want to be equivalent? The static type checking? What do you mean by "class variables"? Scala doesn't have class variables. What do you mean by "without creating class instances"? In Scala, every value is an object, and every object is an instance of a class. – Jörg W Mittag Jul 15 '18 at 21:03
The current, modern way to do this (as of Python 3.7) is with a data class. For example, the Scala case class Point(x: Int, y: Int)
becomes:
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
The frozen=True
part is optional; you can omit it to get a mutable data class. I've included it for parity with Scala's case class.
Before Python 3.7, there's collections.namedtuple
:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
Namedtuples are immutable, as they are tuples. If you want to add methods, you can extend the namedtuple:
class Point(namedtuple('Point', ['x', 'y'])):
def foo():
pass
-
-
1@ecoe I don't know lenses, but you can always post another question to find out. – Brian McCutchon Feb 25 '19 at 0:11
If you use python3.7
you get data classes as @dataclass
. Official doc here - 30.6. dataclasses — Data Classes
from dataclasses import dataclass
@dataclass
class CustomerOrder:
order_id: int
customer_id: str
item_name: str
order = CustomerOrder(1, '001', 'Guitar')
print(order)
Make sure to upgrade python3 to python 3.7 or if you use python 3.6 install dataclass from pypi
In macos: brew upgrade python3
While above data class in scala looks like,
scala> final case class CustomerOrder(id: Int, customerID: String, itemName: String)
defined class CustomerOrder