Python Pipe
From pipe
in Python to The introduction of Functional Programming
All the source code for section 1 is available for this GitHub repo.
Pipe Tutorial
Pipe in Command Line
In command line, pipe (|
) is used to connect different commands, where the input of subsequent commands is the output of previous commands.
For example, the commands below are basic demos of pipe:
1 |
|
Pipe Coding in Python
Installation
1 |
|
Basic Usage
Official GitHub Repo: Repo for Pipe
Website for pypi: Pipe in pypi
Basic Syntax
The same as what you use in the shell!
1 |
|
You can pass arguments in an easier way.
1 |
|
Making it more complex…
1 |
|
generator in Python
Generators in Python offer significant advantages, primarily due to their lazy evaluation and memory efficiency. Unlike functions that return entire lists or other collections, generators yield one item at a time, on demand.
This “yield-as-you-go“ approach means that generators don’t store all their values in memory simultaneously. For instance, when processing a massive dataset, a generator won’t try to load everything at once, which could quickly exhaust your system’s RAM. Instead, it computes and provides values only when requested, making them ideal for handling large or even infinite data streams without overwhelming memory resources.
iterable in Python
If an object is iterable, it means it implements the iter method (which returns an iterator) or the getitem method (which allows access to elements by index, like lists do).
where
for filtering
where(predicate)
: filter elements from iterable objects.
predicate
is a function which returns a bool value (true/false).
1 |
|
Built-in filtering dedup
:
Deduplicate values, using the given key function if provided
1 |
|
select
for selecting
Choose a mapping function for every element in an iterable object.
Quite similar to forEach()
method for array in JavaScripts.
1 |
|
Or you can using the map
function, just like javascripts!
1 |
|
Choosing elements
take(n)
: take the firstn
elements from the iterable objects, like thehead
command in Shell scriptsskip(n)
: skip the firstn
elements from the iterable objectsskip_while(predicate)
: using a predicate function to skip certain objects
groupby
method
Using groupby(key_selector)
to select all the elements by groups.
1 |
|
Traversing
Using traverse
in Pipe to traverse an iterable object.
1 |
|
Chaining
Chaining a sequence of iterable objects.
Warning : chain only unfolds an iterable containing ONLY iterables:
1 |
|
Other commands
islice
: slice for iterable objects, which is the same asitertools.islice
.izip
: zipping likeizip
orzip
in Python 3.
We do not need to load all the elements into the RAM, instead, it will slice (start:stop:step
) and return a new iterator.
tee
: tee outputs to the standard output and yield unchanged items, useful for debugging a pipe stage by stage:
1 |
|
Creating my own Pipes
Using the Pipe
class.
1 |
|
Introduction to functional programming
to be done in the future.