Hacker News new | past | comments | ask | show | jobs | submit login

The thing that I keep finding myself wanting in Python is a more structured way to refer to data; fortunately, that's what namedtuple[1] is for.

    >>> DataType = namedtuple("DataType", ["field1", "field2"])
    >>> datum = DataType(1, "a")
    >>> datum
    DataType(field1=1, field2='a')
    >>> datum.field1
    1
    >>> datum.field2
    2
Keeps my code a bit more sensible than constantly indexing into tuples, imo.

[1]: http://docs.python.org/2/library/collections.html#collection...




It was personally strange to start programming in earnest with Python, and think namedtuples (or classes with __slots__) were so cool and efficient, and then learn C and just think "oh yeah. Structs."


What's really missing though is unions with destructuring `case`. Once you start coding in a language with proper unions, it's hard to go back. In python it might look something like this:

    DataType = union({ 'type1': ['field1', 'field2'], 'type2': ['field3'] })

    DataType.type1(val1, val2)
    DataType.type2(val3)

    # pretend syntax
    case datum:
      DataType.type1(a, b):
        doSomethingWith(a, b)
      DataType.type2(c):
        doSomethingWith(c)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: