Pyjo.Collection - Collection

from Pyjo.Collection import Collection

# Manipulate collection
collection = Collection(['just', 'works'])
collection.insert(0, 'it')
print(collection.join("\n"))

# Or import the module, as in Google Python Style Guide

import Pyjo.Collection

# Manipulate collection
collection = Pyjo.Collection.new('just', 'works')
collection.insert(0, 'it')
print(collection.join("\n"))

# Chain methods
collection.map(lambda e: e.capitalize()).shuffle().each(lambda word, num: print(f'{num}: {word}'))

# Use the alternative constructor
from Pyjo.Collection import c
c('a', 'b', 'c').join('/').url_escape().say()

Pyjo.Collection is a list for collections. The class itself takes an iterable, as list does.

# Access list directly to manipulate collection
collection = Pyjo.Collection.new(*range(1, 26))
collection[23] += 100
for e in collection:
    print(e)

# Make a collection of an iterable
collection = Pyjo.Collection.object(range(1, 26))

See also

Pyjoyment, https://mojolicious.org.

Ported from Mojo::Collection of Mojolicious 9.49.

Functions

class Pyjo.Collection.Pyjo_Collection(iterable=(), /)[source]

Pyjo.Collection inherits all methods from list and implements the following new ones.

__aiter__() → AsyncIterator[source]
async for e in collection:
    ...

Same as iterate().

__json__() → list[T][source]
array = collection.__json__()

Alias for to_list().

__repr__() → str[source]

Return repr(self).

compact() → Self[source]
new = collection.compact()

Create a new collection with all elements that are not None and not an empty string.

# "0, 1, 2, 3"
c(0, 1, None, 2, '', 3).compact().join(', ')
each() → list[T][source]
each(cb: Callable[[T, int], Any]) → Self
elements = collection.each()
collection = collection.each(lambda e, num: ...)

Evaluate callback for each element in collection, or return all elements as a list if none has been provided. The element will be the first argument passed to the callback, and its number the second.

# Make a numbered list
collection.each(lambda e, num: print(f'{num}: {e}'))
first(cb: Callable[[T], Anything] | None = None, /) → T | None[source]
first(cb: Callable[[...], Any] | str | Pattern[str], /, *args: Any, **kwargs: Any) → T | None
first = collection.first()
first = collection.first(re.compile(r'foo'))
first = collection.first(lambda e: ...)
first = collection.first('some_method')
first = collection.first('some_method', *args)

Evaluate regular expression/callback for, or call method on, each element in collection and return the first one that matched the regular expression, or for which the callback/method returned true. The element will be the first argument passed to the callback.

# Longer version
first = collection.first(lambda e: e.some_method(*args))

# Find first value that contains the word "pyjo"
interesting = collection.first(re.compile(r'pyjo', re.I))

# Find first value that is greater than 5
greater = collection.first(lambda e: e > 5)
flatten() → Pyjo_Collection[Any][source]
new = collection.flatten()

Flatten nested collections/lists/tuples recursively and create a new collection with all elements.

# "1, 2, 3, 4, 5, 6, 7"
c(1, [2, [3, 4], 5, [6]], 7).flatten().join(', ')
get(index: int) → T | None[source]
get(index: int, default: D) → T | D
element = collection.get(index)
element = collection.get(index, default)

Return the element at the index, or the default, which is None unless given, if there is no such element. A negative index counts from the end.

import sys
from Pyjo.Util import die
address = c(*sys.argv).get(1) or die('address missing')
port = int(c(*sys.argv).get(2, '80'))
grep(cb: Callable[[T], Anything], /) → Self[source]
grep(cb: Callable[[...], Any] | str | Pattern[str], /, *args: Any, **kwargs: Any) → Self
new = collection.grep(re.compile(r'foo'))
new = collection.grep(lambda e: ...)
new = collection.grep('some_method')
new = collection.grep('some_method', *args)

Evaluate regular expression/callback for, or call method on, each element in collection and create a new collection with all elements that matched the regular expression, or for which the callback/method returned true. The element will be the first argument passed to the callback.

# Longer version
new = collection.grep(lambda e: e.some_method(*args))

# Find all values that contain the word "pyjo"
interesting = collection.grep(re.compile(r'pyjo', re.I))

# Find all values that are greater than 5
greater = collection.grep(lambda e: e > 5)
head(size: int) → Self[source]
new = collection.head(4)
new = collection.head(-2)

Create a new collection with up to the specified number of elements from the beginning of the collection. A negative number will count from the end.

# "A B C"
c('A', 'B', 'C', 'D', 'E').head(3).join(' ')

# "A B"
c('A', 'B', 'C', 'D', 'E').head(-3).join(' ')
iterate() → Pyjo.Iterator.object[T][source]
iterator = collection.iterate()

Turn collection into a lazy Pyjo.Iterator, whose chain passes each element on as soon as it has it, and waits for the promises of its callbacks.

# "2, 4, 6"
c(1, 2, 3).iterate().map(lambda e: e * 2).join(', ')

# Perform 3 requests at a time concurrently, in a coroutine
async for tx in c(*urls).iterate().map(ua.get_p, concurrency=3):
    print(tx.result.dom().at('title').text)
join(string: str | None = None) → Pyjo_String_Unicode[source]
string = collection.join()
string = collection.join("\n")

Turn collection into Pyjo.String.Unicode.

# Join all values with commas
collection.join(', ').say()
last() → T | None[source]
last = collection.last()

Return the last element in collection.

map(cb: Callable[[T], U], /) → Pyjo_Collection[U][source]
map(cb: Callable[[...], Any] | str, /, *args: Any, **kwargs: Any) → Pyjo_Collection[Any]
new = collection.map(lambda e: ...)
new = collection.map('some_method')
new = collection.map('some_method', *args)

Evaluate callback for, or call method on, each element in collection and create a new collection from the results. The element will be the first argument passed to the callback.

# Longer version
new = collection.map(lambda e: e.some_method(*args))

# Append the word "pyjo" to all values
pyjoified = collection.map(lambda e: e + 'pyjo')
classmethod new(*elements: T) → Self[source]
collection = Pyjo.Collection.new(1, 2, 3)

Construct a new Pyjo.Collection object. The constructor of the class takes an iterable, as the one of list, so that a single element that is iterable stays one element of new().

collection = Collection([1, 2, 3])
collection = Collection(n for n in range(3))
reduce(cb: Callable[[Any, T], Any], *initial: Any) → Any[source]
result = collection.reduce(lambda a, b: ...)
result = collection.reduce(lambda a, b: ..., initial)

Reduce elements in collection with a callback and return its final result, passing a and b each time the callback is executed. The first time a will be an optional initial value or the first element in the collection. And from then on a will be the return value of the callback, while b will always be the next element in the collection.

# Calculate the sum of all values
total = collection.reduce(lambda a, b: a + b)

# Count how often each value occurs in collection
counts = collection.reduce(lambda a, b: a | {b: a.get(b, 0) + 1}, {})
reverse() → Self[source]
new = collection.reverse()

Create a new collection with all elements in reverse order.

shuffle() → Self[source]
new = collection.shuffle()

Create a new collection with all elements in random order.

property size: int[source]
size = collection.size

Number of elements in collection.

sort(*, key: Callable[[T], Any] | None = None, reverse: bool = False) → Self[source]
new = collection.sort()
new = collection.sort(key=lambda e: ...)
new = collection.sort(reverse=True)

Sort elements based on return value of a key function and create a new collection from the results, as sorted() does.

# Sort values case-insensitive
case_insensitive = collection.sort(key=str.upper)
tail(size: int) → Self[source]
new = collection.tail(4)
new = collection.tail(-2)

Create a new collection with up to the specified number of elements from the end of the collection. A negative number will count from the beginning.

# "C D E"
c('A', 'B', 'C', 'D', 'E').tail(3).join(' ')

# "D E"
c('A', 'B', 'C', 'D', 'E').tail(-3).join(' ')
tap(cb: Callable[[...], Any] | str, *args: Any, **kwargs: Any) → Self[source]
collection = collection.tap(lambda c: ...)

Alias for Pyjo.Base.tap().

to_dict() → dict[K, V][source]
d = collection.to_dict()

Turn collection of pairs of key and value into dict.

# {'a': 1, 'b': 2, 'c': 3}
c(('a', 1), ('b', 2), ('c', 3)).to_dict()
to_iter() → Iterator[source]
i = collection.to_iter()

Turn collection into an iterator.

for e in c(1, 2, 3).to_iter():
    print(e)
to_list() → list[T][source]
array = collection.to_list()

Turn collection into list.

to_set() → set[T][source]
s = collection.to_set()

Turn collection into set.

# {1, 2, 3}
c(1, 2, 3, 2).to_set()
to_tuple() → tuple[T, ...][source]
t = collection.to_tuple()

Turn collection into tuple.

# (1, 2, 3)
c(1, 2, 3).to_tuple()
uniq(cb: Callable[[...], Any] | str | None = None, *args: Any, **kwargs: Any) → Self[source]
new = collection.uniq()
new = collection.uniq(lambda e: ...)
new = collection.uniq('some_method')
new = collection.uniq('some_method', *args)

Create a new collection without duplicate elements, using the string representation of either the elements or the return value of the callback/method to decide uniqueness. Note that None and empty string are treated the same.

# Longer version
new = collection.uniq(lambda e: e.some_method(*args))

# "foo bar baz"
c('foo', 'bar', 'bar', 'baz').uniq().join(' ')

# [[1, 2], [2, 1]]
c([1, 2], [2, 1], [3, 2]).uniq(lambda e: e[1]).to_list()
zip(iterable: Iterable[U], /, *, strict: bool = False) → Pyjo_Collection[tuple[T, U]][source]
zip(*iterables: Iterable[Any], strict: bool = False) → Pyjo_Collection[tuple[Any, ...]]
new = collection.zip(iterable)
new = collection.zip(iterable, strict=True)

Create a new collection of tuples of the elements of the collection and of the iterables, as zip() does.

# [('a', 1), ('b', 2), ('c', 3)]
c('a', 'b', 'c').zip([1, 2, 3]).to_list()

# {'a': 1, 'b': 2, 'c': 3}
c('a', 'b', 'c').zip([1, 2, 3]).to_dict()
Pyjo.Collection.c(*elements: T) → Pyjo_Collection[source]
collection = c(1, 2, 3)

Construct a new Pyjo.Collection object.

Pyjo.Collection.new(*elements: T) → Self[source]
collection = Pyjo.Collection.new(1, 2, 3)

Construct a new Pyjo.Collection object. The constructor of the class takes an iterable, as the one of list, so that a single element that is iterable stays one element of new().

collection = Collection([1, 2, 3])
collection = Collection(n for n in range(3))