X, Xcall: Elegant Lambda Function Builder

getitem

  • X['key'] equals to lambda obj: obj['key']
>>> from carriage import X, Stream
>>> stm = Stream([{'first name': 'John', 'last name': 'Doe', 'height': 180},
...               {'first name': 'Richard', 'last name': 'Roe', 'height': 190}])
>>> stm.map(X['first name']).to_list()
['John', 'Richard']

getattr

  • X.attr equals to lambda obj: obj.attr
>>> from carriage import X, Stream, Row
>>> stm = Stream([Row(first_name='John', last_name='Doe', height=180),
...               Row(first_name='Richard', last_name='Roe', height=190)])
>>> stm.map(X.last_name).to_list()
['Doe', 'Roe']

Comparison operators

All comparison operators are supported: ==, !=, >, <, >=, <=

  • X > 3 equals to lambda _: _ > 3
  • 'something' != X equals to lambda _: 'something' != _
>>> from carriage import X, Stream, Row
>>> stm = Stream([Row(first_name='John', last_name='Doe', height=180),
...               Row(first_name='Richard', last_name='Roe', height=190),
...               Row(first_name='Jane', last_name='Doe', height=170)])
>>> stm.filter(X.height >= 180).to_list()
[Row(first_name='John', last_name='Doe', height=180), Row(first_name='Richard', last_name='Roe', height=190)]

Math operators

All math and reflected math operators are supported: X + Y, X - Y, X * Y, X / Y, X // Y, X % Y, divmod(X, Y), X**Y, pow(X, Y), abs(X), +X, -X

  • X + 3 equals to lambda num: num + 3
  • 5 // X equals to lambda num: 5 // num
  • pow(2, X) equals to lambda num: pow(2, num)
  • divmod(X, 3) equals to lambda num: divmod(num, 2)
>>> from carriage import X, Stream, Row
>>> stm = Stream([Row(x=5, y=3),
...               Row(x=9, y=3),
...               Row(x=3, y=8)])
>>> stm.map(X.x - X.y).to_list()
[2, 6, -5]

Method/Function calling

  • X.startswith.call('https') equals to lambda url: url.startswith('https')
>>> stm = Stream(['Callum', 'Reuben', 'Taylor', 'Lucas', 'Charles', 'Kylan', 'Camren', 'Edison', 'Raul'])
>>> stm.filter(X.startswith.call('C')).to_list()
['Callum', 'Charles', 'Camren']

As function arguments

  • Xcall(isinstance)(X, int) equals to lambda obj: isinstance(obj, int)
>>> import math
>>> from carriage import X, Stream, Row, Xcall
>>> stm = Stream([Row(x=5, y=3),
...               Row(x=9, y=3),
...               Row(x=3, y=8)])
>>> stm.map(Xcall(math.sqrt)(X.x**2 + X.y**2)).to_list()
[5.830951894845301, 9.486832980505138, 8.54400374531753]

Multiple X

  • X.height + X.width equals to lambda obj: obj.height + obj.width

In collection checking

  • X.in_((1,2)) equals to lambda elem: elem in (1, 2)
  • X.has(1) equals to lambda coll: 1 in coll