Row: Better named tuple for everyday use

class carriage.Row

A named tuple like type without the need of declaring field names in advance.

A Row object can be created anytime when you need it.

>>> Row(name='Joe', age=30, height=170)
Row(name='Joe', age=30, height=170)
>>> Row.from_values([1, 2, 3], fields=['x', 'y', 'z'])
Row(x=1, y=2, z=3)

If you are too lazy to name the fields.

>>> Row.from_values([1, 'a', 9])
Row(f0=1, f1='a', f2=9)

You can access field using index or field name in O(1).

>>> row = Row(name='Joe', age=30, height=170)
>>> row.name
'Joe'
>>> row[2]
170

And it provides some useful method for transforming, converting. Because Row is immutable type, all these method create a new Row object.

>>> row.evolve(height=180)  # I hope so
Row(name='Joe', age=30, height=180)
>>> row.evolve(age=row.age + 1)
Row(name='Joe', age=31, height=170)
>>> row.to_dict()
{'name': 'Joe', 'age': 30, 'height': 170}
>>> row.to_map()
Map({'name': 'Joe', 'age': 30, 'height': 170})

Row is iterable. You can unpack it.

>>> name, age, height = row
>>> name
'Joe'
>>> age
30
evolve(**kwargs)

Create a new Row by replacing or adding other fields

>>> row = Row(x=23, y=9)
>>> row.evolve(y=12)
Row(x=23, y=12)
>>> row.evolve(z=3)
Row(x=23, y=9, z=3)
classmethod from_dict(adict, fields=None)

Create Row from a iterable

>>> Row.from_dict({'name': 'Joe', 'age': 30})
Row(name='Joe', age=30)
classmethod from_values(values, fields=None)

Create Row from values

>>> Row.from_values([1, 2, 3])
Row(f0=1, f1=2, f2=3)
>>> Row.from_values([1, 2, 3], fields=['x', 'y', 'z'])
Row(x=1, y=2, z=3)
get(field, fillvalue=None)

Get field

>>> Row(x=3, y=4).get('x')
3
>>> Row(x=3, y=4).get('z', 0)
0
get_opt(field)

Get field in Optional type

>>> from carriage.optional import Some, Nothing
>>> Row(x=3, y=4).get_opt('x')
Some(3)
>>> Row(x=3, y=4).get_opt('z')
Nothing
Parameters:field (str) – field name
Returns:
  • Just(value) if field exist
  • Nothing if field doesn’t exist
has_field(field)

Has field

>>> Row(x=3, y=4).has_field('x')
True
iter_fields()

Convert to rows

>>> list(Row(x=3, y=4).iter_fields())
[Row(field='x', value=3), Row(field='y', value=4)]
merge(*rows)

Create a new merged Row. If there’s duplicated field name, keep the last value.

>>> row = Row(x=2, y=3)
>>> row.merge(Row(y=4, z=5), Row(z=6, u=7))
Row(x=2, y=4, z=6, u=7)
project(*fields)

Create a new Row by keeping only specified fields

>>> row = Row(x=2, y=3, z=4)
>>> row.project('x', 'y')
Row(x=2, y=3)
rename_fields(**kwargs)

Create a new Row that field names renamed.

>>> row = Row(a=2, b=3, c=4)
>>> row.rename_fields(a='x', b='y')
Row(x=2, y=3, c=4)
to_dict()

Convert to dict

to_fields()

Convert to rows

>>> Row(x=3, y=4).to_fields()
[Row(field='x', value=3), Row(field='y', value=4)]
to_list()

Convert to list

to_map()

Convert to Map

to_tuple()

Convert to tuple

without(*fields)

Create a new Row by removing only specified fields

>>> row = Row(x=2, y=3, z=4)
>>> row.without('z')
Row(x=2, y=3)