fastcore
fastcore is a Python library that 'supercharges' Python for fastai development, but is useful independently. It extends Python with features inspired by other languages like multiple dispatch from Julia, mixins from Ruby, and utilities for functional programming and parallel processing. It aims to eliminate boilerplate and add useful functionality for common tasks, with frequent patch releases.
Warnings
- breaking The multiple dispatch system (`@typedispatch`, `TypeDispatch`) in `fastcore.dispatch` is being replaced by the `plum-dispatch` library. Code relying on fastcore's internal dispatch system will need to be updated.
- gotcha The `fastcore.all.ifnone(a, b)` function eagerly evaluates both `a` and `b`. This differs from Python's standard `b if a is None else a` conditional expression, which short-circuits and only evaluates `b` if `a` is `None`. This can lead to unexpected side effects or performance issues if `b` is a complex or side-effecting operation.
Install
-
pip install fastcore -
conda install fastcore -c fastai
Imports
- fastcore.all
from fastcore.all import *
- typedispatch
from plum import dispatch
Quickstart
import time
from fastcore.all import *
# L: An enhanced list-like object with many utility methods
l_data = L(range(10)).shuffle()
print(f"Original L: {l_data}")
print(f"Filtered (>=5): {l_data.filter(ge(5))}") # 'ge' is an operator function from fastcore.all
# parallel: Easily run functions in parallel
def slow_square(x):
time.sleep(0.01) # Simulate some work
return x*x
results = parallel(slow_square, l_data, n_workers=2)
print(f"Parallel squared results: {results}")
# store_attr and basic_repr: Reduce boilerplate in classes
class MyClass:
def __init__(self, a, b=10):
store_attr() # Automatically stores 'a' and 'b' as self.a, self.b
__repr__ = basic_repr('a,b') # Generates a clean __repr__
obj = MyClass(5, b=20)
print(f"MyClass instance: {obj}")