Python supercharged for fastai development
56
Essential utilities and data structures that form the foundation of the fastcore ecosystem. These include null-safe operations, enhanced dictionaries, attribute access helpers, functional programming tools, and type manipulation utilities.
Core utility functions for common operations including null-safe handling, type checking, and object conversion.
# Global configuration namespace
defaults = SimpleNamespace()
defaults.cpus = num_cpus() # Default number of CPUs for parallel operations
# Special objects for functional programming
Self = _SelfCls() # Special self-reference object
type_map = {int: to_int, float: to_float, str: str, bool: to_bool, date: to_date} # Type conversion mapping
# Argument placeholders for functional composition
arg0 = _Arg(0) # Placeholder for 1st argument
arg1 = _Arg(1) # Placeholder for 2nd argument
arg2 = _Arg(2) # Placeholder for 3rd argument
arg3 = _Arg(3) # Placeholder for 4th argument
arg4 = _Arg(4) # Placeholder for 5th argument
def ifnone(a, b):
"""
Return `b` if `a` is None else `a`.
Parameters:
- a: Value to test for None
- b: Default value if a is None
Returns:
`b` if `a` is None, otherwise `a`
"""
def maybe_attr(o, attr):
"""
Get attribute from object, returning object if attribute doesn't exist.
Equivalent to `getattr(o, attr, o)`.
Parameters:
- o: Object to get attribute from
- attr: Attribute name
Returns:
Attribute value or original object
"""
def is_array(x):
"""
Check if object supports array interface or iloc indexing.
Parameters:
- x: Object to check
Returns:
bool: True if object supports __array__ or iloc
"""
def listify(o=None, *rest, use_list=False, match=None):
"""
Convert object to list if not already iterable.
Parameters:
- o: Object to convert to list
- *rest: Additional objects to include
- use_list: bool, force list return type
- match: Object to match length against
Returns:
List containing the object(s)
"""
def tuplify(o, use_list=False, match=None):
"""
Convert object to tuple if not already iterable.
Parameters:
- o: Object to convert to tuple
- use_list: bool, return list instead of tuple
- match: Object to match length against
Returns:
Tuple containing the object(s)
"""
def true(x):
"""
Test whether object is truthy, handling numpy arrays correctly.
Parameters:
- x: Object to test
Returns:
bool: True if object is truthy
"""Functions and classes for creating string representations and debugging support.
def basic_repr(flds=None):
"""
Create minimal `__repr__` method for a class.
Parameters:
- flds: str or list, field names to include in repr
Returns:
Function that can be used as __repr__ method
"""
class BasicRepr:
"""
Base class that provides basic __repr__ functionality.
Automatically includes class name and key attributes in string representation.
"""
def num_methods(cls):
"""
Count numeric dunder methods in a class.
Parameters:
- cls: Class to inspect
Returns:
int: Number of numeric methods
"""
def rnum_methods(cls):
"""
Count reverse numeric dunder methods in a class.
Parameters:
- cls: Class to inspect
Returns:
int: Number of reverse numeric methods
"""
def inum_methods(cls):
"""
Count in-place numeric dunder methods in a class.
Parameters:
- cls: Class to inspect
Returns:
int: Number of in-place numeric methods
"""Dictionary subclasses with attribute-style access and additional functionality.
class AttrDict(dict):
"""
Dictionary subclass that provides access to keys as attributes.
Features:
- Access keys using dot notation: obj.key
- Set keys using attribute assignment: obj.key = value
- Maintains all standard dict functionality
- Supports copy() method returning new AttrDict
- JSON-friendly repr in Jupyter notebooks
"""
def __getattr__(self, k): ...
def __setattr__(self, k, v): ...
def __dir__(self): ...
def copy(self): ...
class AttrDictDefault(AttrDict):
"""
AttrDict subclass that returns a default value for missing attributes.
Parameters:
- default_: Default value for missing keys (default: None)
Features:
- Returns default_ instead of raising AttributeError
- Useful for configuration objects with optional settings
"""
def __init__(self, *args, default_=None, **kwargs): ...
def __getattr__(self, k): ...
class NS(SimpleNamespace):
"""
Enhanced SimpleNamespace with dict-like interface and iteration support.
Features:
- Iterate over attributes: for key in obj
- Dict-style access: obj[key] and obj[key] = value
- Maintains SimpleNamespace attribute access
"""
def __iter__(self): ...
def __getitem__(self, x): ...
def __setitem__(self, x, y): ...Special object types for representing null values and infinity.
class NullType:
"""
Object that is falsy and can be safely called, chained, and indexed.
Always returns itself for any operation, useful as null object pattern.
Features:
- Falsy: bool(null) is False
- Callable: null() returns null
- Indexable: null[x] returns null
- Attribute access: null.attr returns null
"""
def __call__(self, *args, **kwargs): ...
def __getattr__(self, k): ...
def __getitem__(self, i): ...
def __bool__(self): ...
# Global null instance
null = NullType()
def tonull(x):
"""
Convert object to null if it's falsy, otherwise return unchanged.
Parameters:
- x: Object to potentially convert
Returns:
null if x is falsy, otherwise x
"""
class Inf:
"""
Infinity class that compares greater than any number.
Supports arithmetic operations and maintains infinity properties.
"""
def __lt__(self, other): ...
def __le__(self, other): ...
def __gt__(self, other): ...
def __ge__(self, other): ...Functions for dynamic class creation and object manipulation.
def get_class(nm, *fld_names, sup=None, doc=None, funcs=None, anno=None, **flds):
"""
Create a class with specified name, fields, and methods.
Parameters:
- nm: str, class name
- *fld_names: Field names for the class
- sup: Base class or classes
- doc: str, class docstring
- funcs: dict, methods to add
- anno: dict, type annotations
- **flds: Additional field defaults
Returns:
New class type
"""
def mk_class(nm, *fld_names, sup=None, doc=None, funcs=None, mod=None, anno=None, **flds):
"""
Create class and add to module namespace.
Parameters:
- nm: str, class name
- *fld_names: Field names
- sup: Base class
- doc: str, docstring
- funcs: dict, methods
- mod: Module to add class to
- anno: dict, annotations
- **flds: Field defaults
Returns:
New class type
"""
def wrap_class(nm, *fld_names, sup=None, doc=None, funcs=None, **flds):
"""
Create class as wrapper around existing functionality.
Parameters:
- nm: str, class name
- *fld_names: Field names
- sup: Base class
- doc: str, docstring
- funcs: dict, methods
- **flds: Field defaults
Returns:
New class type
"""Utilities for exception handling and context management.
class ignore_exceptions:
"""
Context manager that ignores specified exceptions.
Parameters:
- *exceptions: Exception types to ignore
Usage:
with ignore_exceptions(ValueError, TypeError):
risky_operation()
"""
def __init__(self, *exceptions): ...
def __enter__(self): ...
def __exit__(self, type, value, traceback): ...
def exec_local(code, var_name):
"""
Execute code and return the value of specified variable.
Parameters:
- code: str, Python code to execute
- var_name: str, variable name to return
Returns:
Value of var_name after code execution
"""Advanced type checking and annotation utilities.
def risinstance(types, obj=None):
"""
Curried isinstance that checks if obj is instance of any of types.
Can be used as partial function or direct check.
Parameters:
- types: Type or tuple of types to check against
- obj: Object to check (optional for currying)
Returns:
Function or bool depending on usage
"""
def ver2tuple(v: str) -> tuple:
"""
Convert version string to tuple for comparison.
Parameters:
- v: str, version string like "1.2.3"
Returns:
tuple: Version as tuple of integers
"""
def get_annotations_ex(obj, *, globals=None, locals=None):
"""
Enhanced annotation extraction with globals/locals support.
Backport of Python 3.10 functionality.
Parameters:
- obj: Object to get annotations from
- globals: dict, global namespace
- locals: dict, local namespace
Returns:
tuple: (annotations_dict, globals, locals)
"""
def type_hints(f):
"""
Get type hints for function, similar to typing.get_type_hints.
Returns empty dict if not allowed type.
Parameters:
- f: Function to get hints for
Returns:
dict: Type hints mapping parameter names to types
"""
def annotations(o):
"""
Get annotations for object or its type/init method.
Parameters:
- o: Object to get annotations for
Returns:
dict: Annotations mapping names to types
"""Helper functions for functional programming patterns.
def ret_true(*args, **kwargs):
"""
Function that always returns True, useful as default predicate.
Returns:
bool: Always True
"""
def ret_false(*args, **kwargs):
"""
Function that always returns False, useful as default predicate.
Returns:
bool: Always False
"""
def stop(e=StopIteration):
"""
Raise specified exception.
Parameters:
- e: Exception instance to raise
Raises:
The provided exception
"""
def gen(func, seq, cond=ret_true):
"""
Generator that applies function to sequence while condition is true.
Parameters:
- func: Function to apply to each item
- seq: Iterable to process
- cond: Predicate function (default: ret_true)
Yields:
Results of func(item) while cond(item) is true
"""
def chunked(it, chunk_sz=None, drop_last=False, n_chunks=None):
"""
Split iterable into chunks of specified size.
Parameters:
- it: Iterable to chunk
- chunk_sz: int, size of each chunk
- drop_last: bool, drop incomplete last chunk
- n_chunks: int, number of chunks (alternative to chunk_sz)
Yields:
Lists containing chunk_sz items each
"""
def otherwise(x, tst, y):
"""
Return y if tst(x) is true, otherwise return x.
Parameters:
- x: Value to test and potentially return
- tst: Predicate function
- y: Alternative value
Returns:
y if tst(x), otherwise x
"""from fastcore.basics import defaults, Self, type_map, arg0, arg1
# Using global defaults
print(f"Default CPU count: {defaults.cpus}")
# Using argument placeholders with bind
from fastcore.basics import bind
def add_multiply(a, b, c):
return (a + b) * c
# Create function with arg placeholders
bound_func = bind(add_multiply, arg0, 10, arg1)
result = bound_func(5, 2) # (5 + 10) * 2 = 30
# Using type conversion mapping
converted = type_map[int]("42") # Converts "42" to integer 42from fastcore.basics import ifnone, listify, AttrDict
# Null-safe operations
config_value = ifnone(user_input, "default_setting")
# List conversion
items = listify("single") # ["single"]
items = listify(None) # []
items = listify([1,2,3]) # [1,2,3]
# Enhanced dictionary
config = AttrDict({
"model_name": "resnet50",
"learning_rate": 0.01,
"batch_size": 32
})
# Access as attributes
print(config.model_name) # "resnet50"
config.epochs = 10 # Set new attribute
config.learning_rate = 0.001 # Modify existingfrom fastcore.basics import risinstance, annotations, type_hints
# Curried isinstance checking
is_numeric = risinstance((int, float))
print(is_numeric(42)) # True
print(is_numeric("42")) # False
# Type introspection
def example_func(x: int, y: str = "default") -> bool:
return True
hints = type_hints(example_func)
# {'x': <class 'int'>, 'y': <class 'str'>, 'return': <class 'bool'>}from fastcore.basics import ignore_exceptions, null
# Ignore specific exceptions
with ignore_exceptions(ValueError, TypeError):
result = risky_conversion(user_data)
# Null object pattern
safe_value = null
result = safe_value.some.deep.attribute.call() # Returns null, no errorsInstall with Tessl CLI
npx tessl i tessl/pypi-fastcoredocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10