Created a Python library to write complex comprehensions and reduce in an easy-to-read manner

I wrote an article like Tips for writing complicated comprehensions in an easy-to-read manner, but I made a library called xcomp based on it. .. Available on Github.

The following are the basic goals.

Installation

pip install git+git://github.com/ukyo-su/xcomp@master

comp(collector)

for xcomp import comp

# a = [i for i in range(5)]Instead of
@comp(list)
def a():
    for i in range(5):
        yield i

# a == [0, 1, 2, 3, 4]

#You can also take the sum. dict and set are also possible
@comp(sum)
def a():
    for i in range(5):
        yield i

# a == 10

#Easy to read even complicated comprehension
@comp(list)
def fizz_buzz():
    for i in range(30):
        if i % 15 == 0:
            yield "Fizz Buzz"
        elif i % 3 == 0:
            yield "Fizz"
        elif i % 5 == 0:
            yield "Buzz"
        else:
            yield i

multi_comp(*collectors) If you want to create multiple collections in one loop.

from xcomp import multi_comp

data = [(0, 1), (2, 3)]

@multi_comp(list, list)
def a():
    for i, j in data:
        yield i, j

a_i, a_j = a

# a_i == [0, 2]
# a_j == [1, 3]

reduce_comp(init, for_=None, for_nest=(), result=lambda x: x)

A decorator to write functools.reduce a little easier to read. Racket [for / fold](https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Ffold% 29% 29) is the original story.

from xcomp import reduce_comp

# reduce(lambda sum_, i: sum_ + i, range(5), 0)
@reduce_comp(0, for_=range(5))
def a(sum_, i):
    return sum_ + i

# a == 10

#Nested for is also OK
@reduce_comp([], for_nest=(range(3), range(2)))
def a(acc, i, j):
    return [*acc, (i, j)]

# a == [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]

#When adding one effort at the end
@reduce_comp([], for_=range(5),
             result=lambda x: list(reversed(x)))
def a(acc, i):
    return [*acc, i]

# a == [4, 3, 2, 1, 0]

# break,also supports continue
@reduce_comp(0, for_=range(100))
def a(acc, i):
    if i > 5:
        raise BreakReduce
    return acc + 1

# a == 6

@reduce_comp(0, for_=range(10))
def a(acc, i):
    if i < 5:
        raise ContinueReduce
    return acc + i

# a == 35

(Is it really easy to read ...?)

multi_reduce_comp(*inits, for_=None, for_nest=(), result=lambda *args: args)

Reduce_comp when there are multiple variables to accumulate. This is close to Racket's for / fold.

@multi_reduce_comp(0, [],
                   for_=range(5))
def a(sum_, rev_list, i):
    return sum_ + i, [i, *rev_list]

a_sum, a_rev_list = a

# a_sum == 10
# a_rev_list == [4, 3, 2, 1, 0]

@multi_reduce_comp([], set(),
                   for_=[0, 1, 1, 2, 3, 4, 4, 4],
                   result=lambda acc, seen: list(reversed(acc)))
def a(acc, seen, i):
    if i in seen:
        return acc, seen
    else:
        return [i, *acc], {*seen, i}

# a == [0, 1, 2, 3, 4]

delay_arg(func, *args, **kwargs)

A higher-order function for turning the first argument to the end. delay_arg (f, * args, ** kwargs) (a) becomes f (a, * args, ** kwargs).

You can use map, filter, reduce as decorators.

@list
@delay_arg(map, range(5))
def a(i):
    return i * 2

# a == [0, 2, 4, 6, 8]

Recommended Posts

Created a Python library to write complex comprehensions and reduce in an easy-to-read manner
Publish / upload a library created in Python to PyPI
[For beginners] How to register a library created in Python in PyPI
[Python] Create a linebot to write a name and age on an image
[Python] Concatenate a List containing numbers and write it to an output file.
A complete guidebook to using pyenv, pip and python in an offline environment
Searching for an efficient way to write a Dockerfile in Python with poetry
I want to write in Python! (2) Let's write a test
Write tests in Python to profile and check coverage
[Python] Created a method to convert radix in 1 second
I want to write a triple loop and conditional branch in one line in python
How to swap elements in an array in Python, and how to reverse an array.
[Python] How to write an if statement in one sentence.
Developed a library to get Kindle collection list in Python
A standard way to develop and distribute packages in Python
I created a class in Python and tried duck typing
How to write a metaclass that supports both python2 and python3
Just try to receive a webhook in ngrok and python
Recursively get the Excel list in a specific folder with python and write it to Excel.
An easy way to view the time taken in Python and a smarter way to improve it
How to write a Python class
How to make a string into an array or an array into a string in Python
A game to go on an adventure in python interactive mode
I created a Python library to call the LINE WORKS API
Write an HTTP / 2 server in Python
Write A * (A-star) algorithm in Python
How to create a heatmap with an arbitrary domain in Python
Difference in how to write if statement between ruby ​​and python
Write a pie chart in Python
Write a vim plugin in Python
Write a depth-first search in Python
An alternative to `pause` in Python
Write a C language linked list in an object-oriented style (with code comparison between Python and Java)
[Python] I tried to summarize the set type (set) in an easy-to-understand manner.
How to send a visualization image of data created in Python to Typetalk
Comparing the basic grammar of Python and Go in an easy-to-understand manner
Let's throw away JavaScript and write a web front end in Python!
How to put a half-width space before letters and numbers in Python.
I tried to summarize Cpaw Level1 & Level2 Write Up in an easy-to-understand manner
Connect to postgreSQL from Python and use stored procedures in a loop.
I want to color a part of an Excel string in Python
How to write a string when there are multiple lines in python
I tried to summarize Cpaw Level 3 Write Up in an easy-to-understand manner
How to stop a program in python until a specific date and time
Write the test in a python docstring
Write a short property definition in Python
Write O_SYNC file in C and Python
How to get a stacktrace in python
Write a Caesar cipher program in Python
Read and write JSON files in Python
Write a simple greedy algorithm in Python
Write a simple Vim Plugin in Python 3
Compress python data and write to sqlite
I created a password tool in Python.
How to use is and == in Python
How to write Ruby to_s in Python
[Python] Created a class to play sin waves in the background with pyaudio
Use libsixel to output Sixel in Python and output a Matplotlib graph to the terminal.
I want to write an element to a file with numpy and check it.
How to use the C library in Python
Organize python modules and packages in a mess