Extension of Builtin Functions¶
Following extended versions of built-in functions are provided.
The function name may be sufficed with _
to avoid name conflict with Python keywords and built-in functions.
Callable Creators¶
- calcpy.arggetter(*keys, default=Missing)[source]¶
Return a callable object that fetches the argument(s) from its operand.
- Parameters:
*keys (int | str) – If it is an
int
(can be negative), it is the index of the positional argument to be fetched. If it is astr
, it is the name of keyword argument to be fetched.default (optional) – Indicate how to return when an argument is not found. If not set, will raise an error when an argument is not found.
- Return type:
callable
- Raises:
IndexError – Raises when the argument is not found and the default is not set.
Examples
Get the first positional argument.
>>> getter = arggetter(0) >>> getter("a", "b", "c", key="value") 'a'
Get the positional arguments and keyword arguments.
>>> getter = arggetter(-1, 0, 1, "key", default="default") >>> getter("a", "b", "c", key="value") ('c', 'a', 'b', 'value')
Get the positional arguments and keyword arguments with default values.
>>> getter = arggetter(-1, 0, 1, 5, "key", "other", default="default") >>> getter("a", "b", "c", key="value") ('c', 'a', 'b', 'default', 'value', 'default')
It will return the key if the key is not found.
>>> from calcpy.fun import skewer >>> lookup = {"a": 1, "b": 2} >>> g = skewer(arggetter(0, 0), lookup.get) # equivalent to lookup.get(x, x) >>> g("a") 1 >>> g("c") 'c'
Raise an error if the index is out of range and the default is not set.
>>> getter = arggetter(0, 1, 2) >>> getter("A", key="value") Traceback (most recent call last): ... IndexError: positional argument index is out of range
- calcpy.attrgetter(*attrs, default=Missing)[source]¶
Return a callable object that fetches the given attribute(s) from its operand.
Fully compatible with Python’s built-in
operator.attrgetter
, and furthermore support an optional default value when a named attr is not found.- Parameters:
*attrs (str) – Attribute names.
default (optional) – Indicate how to return when a named attr is not found. If not set, will raise an error when an attribute is not found.
Examples
Get attributes with default values.
>>> from collections import namedtuple >>> name = namedtuple('Name', ['first', 'last']) >>> name.first = 'Zhiqing' >>> name.last = 'Xiao' >>> person = namedtuple('Person', ['name', 'city']) >>> person.name = name >>> person.city = 'Beijing' >>> g = attrgetter('name.first', 'name.middle', 'name.last', default='') >>> g(person) ('Zhiqing', '', 'Xiao') >>> g = attrgetter('name.first', 'city') >>> g(person) ('Zhiqing', 'Beijing')
It will raise errors when the default is not set.
>>> g = attrgetter('hello') >>> g(sum) Traceback (most recent call last): ... AttributeError: type object 'builtin_function_or_method' has no attribute 'hello'
- calcpy.itemgetter(*items, default=Missing)[source]¶
Return a callable object that fetches the given item(s) from its operand.
Fully compatible with Python’s builtin
operator.itemgetter
, and furthermore support multi-level item and an optional default value when a item is not found.- Parameters:
*items (str) – Keys of items.
default (optional) – Indicate how to return when a named attr is not found. If not set, will raise an error when an item is not found.
Examples
Get multiple items with default values.
>>> person = {'name': {'first': 'Zhiqing', 'last': 'Xiao'}, 'city': 'Beijing'} >>> g = itemgetter(['name', 'first'], ['name', 'middle'], ['name', 'last'], 'city', default='') >>> g(person) ('Zhiqing', '', 'Xiao', 'Beijing') >>> itemgetter(4, default=0)([1, 2, 3]) 0
It will raise errors when the default is not set.
>>> itemgetter(4)([1, 2, 3]) Traceback (most recent call last): ... IndexError: list index out of range
- calcpy.methodcaller(name, *args, **kwargs)[source]¶
Fully compatible with Python’s built-in
operator.methodcaller
.Support
pandas
accessor.Can be decorated by
calcpy.fillerr
when needed to resolve the case where method name is not found.Examples
>>> import pandas as pd >>> s = pd.Series(["a", "b"]) >>> methodcaller("str.upper")(s) 0 A 1 B dtype: object
- calcpy.constantcreator(value, /, copy=False)[source]¶
Callable that returns the same constant when it is called.
- Parameters:
value – Constant value to be returned.
copy – If
True
, return a new copy of the constant value.
- Returns:
Callable object that returns
value
, ignoring its parameters.- Return type:
callable
Examples
Always return the string
"value"
.>>> creator = constantcreator("value") >>> creator() 'value'
Create a pd.DataFrame whose elements are all empty lists.
>>> import pandas as pd >>> df = pd.DataFrame(index=range(3), columns=["A"]) >>> (df.map if hasattr(df, "map") else df.applymap)(constantcreator([])) A 0 [] 1 [] 2 []
Return a new copy when
copy=True
.>>> import pandas as pd >>> df = pd.DataFrame(index=range(3), columns=["A"]) >>> constantcreator(df, copy=True)() is df False
Checkers¶
- calcpy.argchecker(*keys)[source]¶
Return a callable object to check the existences of argument(s).
- Parameters:
*keys (int | str) – If it is an
int
(can be negative), it is the index of the positional argument to be fetched. If it is astr
, it is the name of keyword argument to be fetched.- Return type:
bool | tuple[bool]
Examples
>>> getter = argchecker(-1, 0, 1, 5, "key", "other") >>> getter("a", "b", "c", key="value") (True, True, True, False, True, False)
- calcpy.attrchecker(*attrs)[source]¶
Return a callable object to check the existence of the given attribute(s).
- Parameters:
*attrs (str) – Attribute names.
Examples
>>> c = attrchecker("mro", "type") >>> c(type) (True, False)
>>> import os >>> c = attrchecker("path", "path.sep", "sep.path") >>> c(os) (True, True, False)
- calcpy.itemchecker(*items)[source]¶
Return a callable object to check the existence of the given item(s).
Examples
>>> data = {"name": {"first": "Zhiqing", "last": "Xiao"}, "city": "Beijing"} >>> c = itemchecker(["name", "first"], ["name", "middle"], ["name", "last"], "city", "sex") >>> c(data) (True, False, True, True, False)
>>> itemchecker(-3, 0, 3)([1, 2, 3]) (True, True, False)