Type imitation in python

What is the best way to imitate types in Python?

How this TestResult Haskell datatype could be defined in Python?

data TestResult
  = TestResult {name :: String,
                feature :: String,
                passed :: Bool,
                errorMessage :: String}

I tried that, but it looks kinda silly. Are there another ways to approach that behavior?

class TestResult:
    def __init__(self, name, feature, passed, errorMessage):
        self.name         = name
        self.feature      = feature
        self.passed       = passed
        self.errorMessage = errorMessage

I'm not looking for some type-superfluity, but for something like "type constructor" magic kludge to combine some data stubs in a logically single thing.

Upvotes: 3

Views: 369

Answers (2)

lbolla
lbolla

Reputation: 5411

You code looks good to me. You can look into NamedTuples if you want a less verbose version.

Upvotes: 2

Sven Marnach
Sven Marnach

Reputation: 602635

For immutable data you can use collections.namedtuple:

>>> from collections import namedtuple
>>> TestResult = namedtuple("TestResult", "name feature passed errorMessage")
>>> TestResult("a", "b", True, "c")
TestResult(name='a', feature='b', passed=True, errorMessage='c')

Upvotes: 4

Related Questions