Basic functionality used in the fastai library
-
def ifnone(a, b)
b
ifa
is None elsea
-
def maybe_attr(o, attr)
getattr(o,attr,o)
-
def basic_repr(flds)
Minimal__repr__
-
def is_array(x)
True
ifx
supports__array__
oriloc
-
def listify(o, *rest)
Converto
to alist
-
def tuplify(o, use_list, match)
Makeo
a tuple -
def true(x)
Test whetherx
is truthy; collections with >0 elements are consideredTrue
-
class NullType
An object that isFalse
and can be called, chained, and indexeddef __getattr__(self, *args)
def __call__(self, *args, **kwargs)
def __getitem__(self, *args)
def __bool__(self)
-
def tonull(x)
ConvertNone
tonull
-
def get_class(nm, *fld_names, **flds)
Dynamically create a class, optionally inheriting fromsup
, containingfld_names
-
def mk_class(nm, *fld_names, **flds)
Create a class usingget_class
and add to the caller's module -
def wrap_class(nm, *fld_names, **flds)
Decorator: makes function a method of a new classnm
passing parameters tomk_class
-
class ignore_exceptions
Context manager to ignore exceptionsdef __enter__(self)
def __exit__(self, *args)
-
def exec_local(code, var_name)
Callexec
oncode
and return the varvar_name
-
def risinstance(types, obj)
Curriedisinstance
but with args reversed -
class Inf
Infinite lists -
def in_(x, a)
True
ifx in a
-
def ret_true(*args, **kwargs)
Predicate: alwaysTrue
-
def ret_false(*args, **kwargs)
Predicate: alwaysFalse
-
def stop(e)
Raises exceptione
(by defaultStopIteration
) -
def gen(func, seq, cond)
Like(func(o) for o in seq if cond(func(o)))
but handlesStopIteration
-
def chunked(it, chunk_sz, drop_last, n_chunks)
Return batches from iteratorit
of sizechunk_sz
(or returnn_chunks
total) -
def otherwise(x, tst, y)
y if tst(x) else x
-
def custom_dir(c, add)
Implement custom__dir__
, addingadd
tocls
-
class AttrDict
dict
subclass that also provides access to keys as attrsdef __getattr__(self, k)
def __setattr__(self, k, v)
def __dir__(self)
def copy(self)
-
class AttrDictDefault
AttrDict
subclass that returnsNone
for missing attrsdef __init__(self, *args, **kwargs)
def __getattr__(self, k)
-
class NS
SimpleNamespace
subclass that also addsiter
anddict
supportdef __iter__(self)
def __getitem__(self, x)
def __setitem__(self, x, y)
-
def get_annotations_ex(obj)
Backport of py3.10get_annotations
that returns globals/locals -
def eval_type(t, glb, loc)
eval
a type or collection of types, if needed, for annotations in py3.10+ -
def type_hints(f)
Liketyping.get_type_hints
but returns{}
if not allowed type -
def annotations(o)
Annotations foro
, ortype(o)
-
def anno_ret(func)
Get the return annotation offunc
-
def signature_ex(obj, eval_str)
Backport ofinspect.signature(..., eval_str=True
to <py310 -
def argnames(f, frame)
Names of arguments to function or framef
-
def with_cast(f)
Decorator which uses any parameter annotations as preprocessing functions -
def store_attr(names, self, but, cast, store_args, **attrs)
Store params named in comma-separatednames
from calling context into attrs inself
-
def attrdict(o, *ks)
Dict from eachk
inks
togetattr(o,k)
-
def properties(cls, *ps)
Change attrs incls
with names inps
to properties -
def camel2words(s, space)
Convert CamelCase to 'spaced words' -
def camel2snake(name)
Convert CamelCase to snake_case -
def snake2camel(s)
Convert snake_case to CamelCase -
def class2attr(self, cls_name)
Return the snake-cased name of the class; strip endingcls_name
if it exists. -
def getcallable(o, attr)
Callsgetattr
with a default ofnoop
-
def getattrs(o, *attrs)
List of allattrs
ino
-
def hasattrs(o, attrs)
Test whethero
contains allattrs
-
def try_attrs(obj, *attrs)
Return first attr that exists inobj
-
class GetAttrBase
Basic delegation of__getattr__
and__dir__
def __getattr__(self, k)
def __dir__(self)
-
class GetAttr
Inherit from this to have all attr accesses inself._xtra
passed down toself.default
def __getattr__(self, k)
def __dir__(self)
def __setstate__(self, data)
-
def delegate_attr(self, k, to)
Use in__getattr__
to delegate to attrto
without inheriting fromGetAttr
-
class ShowPrint
Base class that prints forshow
def show(self, *args, **kwargs)
-
class Int
An extensibleint
-
class Str
An extensiblestr
-
class Float
An extensiblefloat
-
def partition(coll, f)
Partition a collection by a predicate -
def flatten(o)
Concatenate all collections and items as a generator -
def concat(colls)
Concatenate all collections and items as a list -
def strcat(its, sep)
Concatenate stringified itemsits
-
def detuplify(x)
Ifx
is a tuple with one thing, extract it -
def replicate(item, match)
Create tuple ofitem
copiedlen(match)
times -
def setify(o)
Turn any list like-object into a set. -
def merge(*ds)
Merge all dictionaries inds
-
def range_of(x)
All indices of collectionx
(i.e.list(range(len(x)))
) -
def groupby(x, key, val)
Likeitertools.groupby
but doesn't need to be sorted, and isn't lazy, plus some extensions -
def last_index(x, o)
Finds the last index of occurence ofx
ino
(returns -1 if no occurence) -
def filter_dict(d, func)
Filter adict
usingfunc
, applied to keys and values -
def filter_keys(d, func)
Filter adict
usingfunc
, applied to keys -
def filter_values(d, func)
Filter adict
usingfunc
, applied to values -
def cycle(o)
Likeitertools.cycle
except creates list ofNone
s ifo
is empty -
def zip_cycle(x, *args)
Likeitertools.zip_longest
butcycle
s through elements of all but first argument -
def sorted_ex(iterable, key, reverse)
Likesorted
, but if key is str useattrgetter
; if int useitemgetter
-
def not_(f)
Create new function that negates result off
-
def argwhere(iterable, f, negate, **kwargs)
Likefilter_ex
, but return indices for matching items -
def filter_ex(iterable, f, negate, gen, **kwargs)
Likefilter
, but passingkwargs
tof
, defaultingf
tonoop
, and addingnegate
andgen
-
def renumerate(iterable, start)
Same asenumerate
, but returns index as 2nd element instead of 1st -
def first(x, f, negate, **kwargs)
First element ofx
, optionally filtered byf
, or None if missing -
def only(o)
Return the only item ofo
, raise ifo
doesn't have exactly one item -
def nested_attr(o, attr, default)
Same asgetattr
, but ifattr
includes a.
, then looks inside nested objects -
def nested_setdefault(o, attr, default)
Same assetdefault
, but ifattr
includes a.
, then looks inside nested objects -
def nested_callable(o, attr)
Same asnested_attr
but if not found will returnnoop
-
def nested_idx(coll, *idxs)
Index into nested collections, dicts, etc, withidxs
-
def set_nested_idx(coll, value, *idxs)
Set value indexed like `nested_idx -
def val2idx(x)
Dict from value to index -
def uniqueify(x, sort, bidir, start)
Unique elements inx
, optionalsort
, optional return reverse correspondence, optional prepend with elements. -
def loop_first_last(values)
Iterate and generate a tuple with a flag for first and last value. -
def loop_first(values)
Iterate and generate a tuple with a flag for first value. -
def loop_last(values)
Iterate and generate a tuple with a flag for last value. -
def first_match(lst, f, default)
First element oflst
matching predicatef
, ordefault
if none -
def last_match(lst, f, default)
Last element oflst
matching predicatef
, ordefault
if none -
class fastuple
Atuple
with elementwise ops and more friendly init behavior-
def __new__(cls, x, *rest)
-
def mul(self, *args)
*
is already defined intuple
for replicating, so usemul
instead -
def add(self, *args)
+
is already defined intuple
for concat, so useadd
instead
-
-
class bind
Same aspartial
, except you can usearg0
arg1
etc param placeholdersdef __init__(self, func, *pargs, **pkwargs)
def __call__(self, *args, **kwargs)
-
def mapt(func, *iterables)
Tuplifiedmap
-
def map_ex(iterable, f, *args, **kwargs)
Likemap
, but usebind
, and supportsstr
and indexing -
def compose(*funcs)
Create a function that composes all functions infuncs
, passing along remaining*args
and**kwargs
to all -
def maps(*args)
Likemap
, except funcs are composed first -
def partialler(f, *args, **kwargs)
Likefunctools.partial
but also copies over docstring -
def instantiate(t)
Instantiatet
if it's a type, otherwise do nothing -
def using_attr(f, attr)
Construct a function which appliesf
to the argument's attributeattr
-
def copy_func(f)
Copy a non-builtin function (NBcopy.copy
does not work for this) -
def patch_to(cls, as_prop, cls_method)
Decorator: addf
tocls
-
def patch(f)
Decorator: addf
to the first parameter's class (based on f's type annotations) -
def patch_property(f)
Deprecated; usepatch(as_prop=True)
instead -
def compile_re(pat)
Compilepat
if it's not None -
class ImportEnum
AnEnum
that can have its values imported@classmethod def imports(cls)
@property def name(self)
-
class StrEnum
AnImportEnum
that behaves like astr
def __str__(self)
@property def name(self)
-
def str_enum(name, *vals)
Simplified creation ofStrEnum
types -
class ValEnum
AnImportEnum
that stringifies using valuesdef __str__(self)
@property def name(self)
-
class Stateful
A base class/mixin for objects that should not serialize all their statedef __init__(self, *args, **kwargs)
def __getstate__(self)
def __setstate__(self, state)
-
class NotStr
Behaves like astr
, but isn't an instance of onedef __init__(self, s)
def __repr__(self)
def __str__(self)
def __add__(self, b)
def __mul__(self, b)
def __len__(self)
def __eq__(self, b)
def __lt__(self, b)
def __hash__(self)
def __bool__(self)
def __contains__(self, b)
def __iter__(self)
-
class PrettyString
Little hack to get strings to show properly in Jupyter.def __repr__(self)
-
def even_mults(start, stop, n)
Build log-stepped array fromstart
tostop
inn
steps. -
def num_cpus()
Get number of cpus -
def add_props(f, g, n)
Create properties passing each ofrange(n)
to f -
def typed(f)
Decorator to check param and return types at runtime -
def exec_new(code)
Executecode
in a new environment and return it -
def exec_import(mod, sym)
Importsym
frommod
in a new environment -
def str2bool(s)
Case-insensitive convert strings
too a bool (y
,yes
,t
,true
,on
,1
->True
)
Basic single and dual parameter dispatch
-
def lenient_issubclass(cls, types)
If possible return whethercls
is a subclass oftypes
, otherwise return False. -
def sorted_topologically(iterable)
Return a new list containing all items from the iterable sorted topologically -
class TypeDispatch
Dictionary-like object;__getitem__
matches keys of types usingissubclass
-
def __init__(self, funcs, bases)
-
def add(self, f)
Add typet
and functionf
-
def first(self)
Get first function in ordered dict of type:func. -
def returns(self, x)
Get the return type of annotation ofx
. -
def __repr__(self)
-
def __call__(self, *args, **kwargs)
-
def __get__(self, inst, owner)
-
def __getitem__(self, k)
Find first matching type that is a super-class ofk
-
-
class DispatchReg
A global registry forTypeDispatch
objects keyed by function namedef __init__(self)
def __call__(self, f)
-
def retain_meta(x, res, as_copy)
Callres.set_meta(x)
, if it exists -
def default_set_meta(self, x, as_copy)
Copy over_meta
fromx
tores
, if it's missing -
@typedispatch def cast(x, typ)
castx
to typetyp
(may also changex
inplace) -
def retain_type(new, old, typ, as_copy)
Castnew
to type ofold
ortyp
if it's a superclass -
def retain_types(new, old, typs)
Cast each item ofnew
to type of matching item inold
if it's a superclass -
def explode_types(o)
Return the type ofo
, potentially in nested dictionaries for thing that are listy
Document parameters using comments.
-
def docstring(sym)
Get docstring forsym
for functions ad classes -
def parse_docstring(sym)
Parse a numpy-style docstring insym
-
def isdataclass(s)
Check ifs
is a dataclass but not a dataclass' instance -
def get_dataclass_source(s)
Get source code for dataclasss
-
def get_source(s)
Get source code for string, function object or dataclasss
-
def get_name(obj)
Get the name ofobj
-
def qual_name(obj)
Get the qualified name ofobj
-
@delegates(_docments) def docments(elt, full, **kwargs)
Generates adocment
-
def extract_docstrings(code)
Create a dict from function/class/method names to tuples of docstrings and param lists
Parse numpy-style docstrings
-
def strip_blank_lines(l)
Remove leading and trailing blank lines from a list of lines -
class Reader
A line-based string reader.def __init__(self, data)
def __getitem__(self, n)
def reset(self)
def read(self)
def seek_next_non_empty_line(self)
def eof(self)
def read_to_condition(self, condition_func)
def read_to_next_empty_line(self)
def read_to_next_unindented_line(self)
def peek(self, n)
def is_empty(self)
-
class ParseError
def __str__(self)
-
class NumpyDocString
Parses a numpydoc string to an abstract representationdef __init__(self, docstring, config)
def __iter__(self)
def __len__(self)
def __getitem__(self, key)
def __setitem__(self, key, val)
-
def dedent_lines(lines, split)
Deindent a list of lines maximally
The
L
class and helpers for it
-
@contextmanager def working_directory(path)
Change working directory topath
and return to previous on exit. This is a multi-line docstring. Ok this is a different line even. -
def add_docs(cls, cls_doc, **docs)
Copy values fromdocs
tocls
docstrings, and confirm all public methods are documented -
def docs(cls)
Decorator version ofadd_docs
, using_docs
dict -
def coll_repr(c, max_n)
String repr of up tomax_n
items of (possibly lazy) collectionc
-
def is_bool(x)
Check whetherx
is a bool or None -
def mask2idxs(mask)
Convert bool mask or index list to indexL
-
def is_indexer(idx)
Test whetheridx
will index a single item in a list -
class CollBase
Base class for composing a list ofitems
def __init__(self, items)
def __len__(self)
def __getitem__(self, k)
def __setitem__(self, k, v)
def __delitem__(self, i)
def __repr__(self)
def __iter__(self)
-
class L
Behaves like a list ofitems
but can also index with list of indices or masks-
def __init__(self, items, *rest)
-
def __getitem__(self, idx)
-
def copy(self)
-
def __setitem__(self, idx, o)
Setidx
(can be list of indices, or mask, or int) items too
(which is broadcast if not iterable) -
def __eq__(self, b)
-
def sorted(self, key, reverse)
-
def __iter__(self)
-
def __contains__(self, b)
-
def __reversed__(self)
-
def __invert__(self)
-
def __repr__(self)
-
def __mul__(a, b)
-
def __add__(a, b)
-
def __radd__(a, b)
-
def __addi__(a, b)
-
@classmethod def split(cls, s, sep, maxsplit)
-
@classmethod def range(cls, a, b, step)
-
def map(self, f, *args, **kwargs)
-
def argwhere(self, f, negate, **kwargs)
-
def argfirst(self, f, negate)
-
def filter(self, f, negate, **kwargs)
-
def enumerate(self)
-
def renumerate(self)
-
def unique(self, sort, bidir, start)
-
def val2idx(self)
-
def cycle(self)
-
def map_dict(self, f, *args, **kwargs)
-
def map_first(self, f, g, *args, **kwargs)
-
def itemgot(self, *idxs)
-
def attrgot(self, k, default)
-
def starmap(self, f, *args, **kwargs)
-
def zip(self, cycled)
-
def zipwith(self, *rest)
-
def map_zip(self, f, *args, **kwargs)
-
def map_zipwith(self, f, *rest, **kwargs)
-
def shuffle(self)
-
def concat(self)
-
def reduce(self, f, initial)
-
def sum(self)
-
def product(self)
-
def setattrs(self, attr, val)
-
-
def save_config_file(file, d, **kwargs)
Write settings dict to a new config file, or overwrite the existing one. -
class Config
Reading and writingConfigParser
ini filesdef __init__(self, cfg_path, cfg_name, create, save, extra_files, types)
def __repr__(self)
def __setitem__(self, k, v)
def __contains__(self, k)
def save(self)
def __getattr__(self, k)
def __getitem__(self, k)
def get(self, k, default)
def path(self, k, default)
Recognize image file formats based on their first few bytes.
-
def test_jpeg(h, f)
JPEG data with JFIF or Exif markers; and raw JPEG -
def test_gif(h, f)
GIF ('87 and '89 variants) -
def test_tiff(h, f)
TIFF (can be in Motorola or Intel byte order) -
def test_rgb(h, f)
SGI image library -
def test_pbm(h, f)
PBM (portable bitmap) -
def test_pgm(h, f)
PGM (portable graymap) -
def test_ppm(h, f)
PPM (portable pixmap) -
def test_rast(h, f)
Sun raster file -
def test_xbm(h, f)
X bitmap (X10 or X11)
-
def is_iter(o)
Test whethero
can be used in afor
loop -
def is_coll(o)
Test whethero
is a collection (i.e. has a usablelen
) -
def all_equal(a, b)
Compares whethera
andb
are the same length and have the same contents -
def noop(x, *args, **kwargs)
Do nothing -
def noops(self, x, *args, **kwargs)
Do nothing (method) -
def isinstance_str(x, cls_name)
Likeisinstance
, except takes a type name instead of a type -
def equals(a, b)
Comparesa
andb
for equality; supports sublists, tensors and arrays too -
def ipython_shell()
Same asget_ipython
but returnsFalse
if not in IPython -
def in_ipython()
Check if code is running in some kind of IPython environment -
def in_colab()
Check if the code is running in Google Colaboratory -
def in_jupyter()
Check if the code is running in a jupyter notebook -
def in_notebook()
Check if the code is running in a jupyter notebook -
def remove_prefix(text, prefix)
Temporary until py39 is a prereq -
def remove_suffix(text, suffix)
Temporary until py39 is a prereq
Metaclasses
-
def test_sig(f, b)
Test the signature of an object -
class FixSigMeta
A metaclass that fixes the signature on classes that override__new__
def __new__(cls, name, bases, dict)
-
class PrePostInitMeta
A metaclass that calls optional__pre_init__
and__post_init__
methodsdef __call__(cls, *args, **kwargs)
-
class AutoInit
Same asobject
, but no need for subclasses to callsuper().__init__
def __pre_init__(self, *args, **kwargs)
-
class NewChkMeta
Metaclass to avoid recreating object passed to constructordef __call__(cls, x, *args, **kwargs)
-
class BypassNewMeta
Metaclass: castsx
to this class if it's of typecls._bypass_type
def __call__(cls, x, *args, **kwargs)
-
def empty2none(p)
ReplaceParameter.empty
withNone
-
def anno_dict(f)
__annotation__ dictionary with
emptycast to
None`, returning empty if doesn't exist -
def use_kwargs_dict(keep, **kwargs)
Decorator: replace**kwargs
in signature withnames
params -
def use_kwargs(names, keep)
Decorator: replace**kwargs
in signature withnames
params -
def delegates(to, keep, but)
Decorator: replace**kwargs
in signature with params fromto
-
def method(f)
Markf
as a method -
def funcs_kwargs(as_method)
Replace methods incls._methods
with those fromkwargs
Network, HTTP, and URL functions
-
def urlquote(url)
Update url's path withurllib.parse.quote
-
def urlwrap(url, data, headers)
Wrapurl
in a urllibRequest
withurlquote
-
class HTTP4xxClientError
Base class for client exceptions (code 4xx) fromurl*
functions -
class HTTP5xxServerError
Base class for server exceptions (code 5xx) fromurl*
functions -
def urlopen(url, data, headers, timeout, **kwargs)
Likeurllib.request.urlopen
, but firsturlwrap
theurl
, and encodedata
-
def urlread(url, data, headers, decode, return_json, return_headers, timeout, **kwargs)
Retrieveurl
, usingdata
dict orkwargs
toPOST
if present -
def urljson(url, data, timeout)
Retrieveurl
and decode json -
def urlclean(url)
Remove fragment, params, and querystring fromurl
if present -
def urlsave(url, dest, reporthook, headers, timeout)
Retrieveurl
and save based on its name -
def urlvalid(x)
Test ifx
is a valid URL -
def urlrequest(url, verb, headers, route, query, data, json_data)
Request
forurl
with optional route params replaced byroute
, plusquery
string, and postdata
-
@patch def summary(self, skip)
Summary containing full_url, headers, method, and data, removingskip
from headers -
def urlsend(url, verb, headers, decode, route, query, data, json_data, return_json, return_headers, debug, timeout)
Send request withurlrequest
, converting result to json ifreturn_json
-
def do_request(url, post, headers, **data)
Call GET or json-encoded POST onurl
, depending onpost
-
def start_server(port, host, dgram, reuse_addr, n_queue)
Create asocket
server onport
, with optionalhost
, of typedgram
-
def start_client(port, host, dgram)
Create asocket
client onport
, with optionalhost
, of typedgram
-
def tobytes(s)
Converts
into HTTP-ready bytes format -
def http_response(body, status, hdrs, **kwargs)
Create an HTTP-ready response, addingkwargs
tohdrs
-
@threaded def recv_once(host, port)
Spawn a thread to receive a single HTTP request and store ind['r']
Threading and multiprocessing functions
-
def threaded(process)
Runf
in aThread
(orProcess
ifprocess=True
), and returns it -
def startthread(f)
Likethreaded
, but start thread immediately -
def startproc(f)
Likethreaded(True)
, but start Process immediately -
class ThreadPoolExecutor
Same as Python's ThreadPoolExecutor, except can passmax_workers==0
for serial executiondef __init__(self, max_workers, on_exc, pause, **kwargs)
def map(self, f, items, *args, **kwargs)
-
@delegates() class ProcessPoolExecutor
Same as Python's ProcessPoolExecutor, except can passmax_workers==0
for serial executiondef __init__(self, max_workers, on_exc, pause, **kwargs)
def map(self, f, items, *args, **kwargs)
-
def parallel(f, items, *args, **kwargs)
Appliesfunc
in parallel toitems
, usingn_workers
-
def run_procs(f, f_done, args)
Callf
for each item inargs
in parallel, yieldingf_done
-
def parallel_gen(cls, items, n_workers, **kwargs)
Instantiatecls
inn_workers
procs & call each on a subset ofitems
in parallel.
-
def imp_mod(module_path, package)
Import dynamically the module referenced infn
-
def has_deco(node, name)
Check if a function nodenode
has a decorator namedname
-
def create_pyi(fn, package)
Convertfname.py
tofname.pyi
by removing function bodies and expandingdelegates
kwargs -
@call_parse def py2pyi(fname, package)
Convertfname.py
tofname.pyi
by removing function bodies and expandingdelegates
kwargs -
@call_parse def replace_wildcards(path)
Expand wildcard imports in the specified Python file.
A fast way to turn your python function into a script.
-
def store_true()
Placeholder to pass toParam
forstore_true
action -
def store_false()
Placeholder to pass toParam
forstore_false
action -
def bool_arg(v)
Use astype
forParam
to getbool
behavior -
class Param
A parameter in a function used inanno_parser
orcall_parse
def __init__(self, help, type, opt, action, nargs, const, choices, required, default)
def set_default(self, d)
@property def pre(self)
@property def kwargs(self)
def __repr__(self)
-
def anno_parser(func, prog)
Look at params (annotated withParam
) in func and return anArgumentParser
-
def args_from_prog(func, prog)
Extract args fromprog
-
def call_parse(func, nested)
Decorator to create a simple CLI fromfunc
usinganno_parser
Fast styling for friendly CLIs.
-
class StyleCode
An escape sequence for styling terminal text.def __init__(self, name, code, typ)
def __str__(self)
-
class Style
A minimal terminal text styler.def __init__(self, codes)
def __dir__(self)
def __getattr__(self, k)
def __call__(self, obj)
def __repr__(self)
-
def demo()
Demonstrate all available styles and their codes.
Helper functions to quickly write tests in notebooks
-
def test_fail(f, msg, contains, args, kwargs)
Fails withmsg
unlessf()
raises an exception and (optionally) hascontains
ine.args
-
def test(a, b, cmp, cname)
assert
thatcmp(a,b)
; display inputs andcname or cmp.__name__
if it fails -
def nequals(a, b)
Comparesa
andb
fornot equals
-
def test_eq(a, b)
test
thata==b
-
def test_eq_type(a, b)
test
thata==b
and are same type -
def test_ne(a, b)
test
thata!=b
-
def is_close(a, b, eps)
Isa
withineps
ofb
-
def test_close(a, b, eps)
test
thata
is withineps
ofb
-
def test_is(a, b)
test
thata is b
-
def test_shuffled(a, b)
test
thata
andb
are shuffled versions of the same sequence of items -
def test_stdout(f, exp, regex)
Test thatf
printsexp
to stdout, optionally checking asregex
-
def test_fig_exists(ax)
Test there is a figure displayed inax
-
class ExceptionExpected
Context manager that tests if an exception is raiseddef __init__(self, ex, regex)
def __enter__(self)
def __exit__(self, type, value, traceback)
Definition of
Transform
andPipeline
-
class Transform
Delegates (__call__
,decode
,setup
) to (encodes
,decodes
,setups
) ifsplit_idx
matchesdef __init__(self, enc, dec, split_idx, order)
@property def name(self)
def __call__(self, x, **kwargs)
def decode(self, x, **kwargs)
def __repr__(self)
def setup(self, items, train_setup)
-
class InplaceTransform
ATransform
that modifies in-place and just returns whatever it's passed -
class DisplayedTransform
A transform with a__repr__
that shows its attrs@property def name(self)
-
class ItemTransform
A transform that always take tuples as itemsdef __call__(self, x, **kwargs)
def decode(self, x, **kwargs)
-
def get_func(t, name, *args, **kwargs)
Get thet.name
(potentially partial-ized withargs
andkwargs
) ornoop
if not defined -
class Func
Basic wrapper around aname
withargs
andkwargs
to call on a given typedef __init__(self, name, *args, **kwargs)
def __repr__(self)
def __call__(self, t)
-
def compose_tfms(x, tfms, is_enc, reverse, **kwargs)
Apply allfunc_nm
attribute oftfms
onx
, maybe inreverse
order -
def mk_transform(f)
Convert functionf
toTransform
if it isn't already one -
def gather_attrs(o, k, nm)
Used in getattr to collect all attrsk
fromself.{nm}
-
def gather_attr_names(o, nm)
Used in dir to collect all attrsk
fromself.{nm}
-
class Pipeline
A pipeline of composed (for encode/decode) transforms, setup with typesdef __init__(self, funcs, split_idx)
def setup(self, items, train_setup)
def add(self, ts, items, train_setup)
def __call__(self, o)
def __repr__(self)
def __getitem__(self, i)
def __setstate__(self, data)
def __getattr__(self, k)
def __dir__(self)
def decode(self, o, full)
def show(self, o, ctx, **kwargs)
XDG Base Directory Specification helpers.
-
def xdg_cache_home()
Path corresponding toXDG_CACHE_HOME
-
def xdg_config_dirs()
Paths corresponding toXDG_CONFIG_DIRS
-
def xdg_config_home()
Path corresponding toXDG_CONFIG_HOME
-
def xdg_data_dirs()
Paths corresponding to XDG_DATA_DIRS` -
def xdg_data_home()
Path corresponding toXDG_DATA_HOME
-
def xdg_runtime_dir()
Path corresponding toXDG_RUNTIME_DIR
-
def xdg_state_home()
Path corresponding toXDG_STATE_HOME
Concise generation of XML.
-
class FT
A 'Fast Tag' structure, containingtag
,children
,andattrs
def __init__(self, tag, cs, attrs, void_, **kwargs)
def __setattr__(self, k, v)
def __getattr__(self, k)
@property def list(self)
def get(self, k, default)
def __repr__(self)
def __add__(self, b)
def __getitem__(self, idx)
def __iter__(self)
-
def ft(tag, *c, **kw)
Create anFT
structure forto_xml()
-
def Html(*c, **kwargs)
An HTML tag, optionally preceeded by!DOCTYPE HTML
-
class Safe
def __html__(self)
-
def to_xml(elm, lvl, indent, do_escape)
Convertft
element tree into an XML string -
def highlight(s, lang)
Markdown to syntax-highlights
in languagelang
Utility functions used in the fastai library
-
def walk(path, symlinks, keep_file, keep_folder, skip_folder, func, ret_folders)
Generator version ofos.walk
, using functions to filter files and folders -
def globtastic(path, recursive, symlinks, file_glob, file_re, folder_re, skip_file_glob, skip_file_re, skip_folder_re, func, ret_folders)
A more powerfulglob
, including regex matches, symlink handling, and skip parameters -
@contextmanager def maybe_open(f, mode, **kwargs)
Context manager: openf
if it is a path (and close on exit) -
def mkdir(path, exist_ok, parents, overwrite, **kwargs)
Creates and returns a directory defined bypath
, optionally removing previous existing directory ifoverwrite
isTrue
-
def image_size(fn)
Tuple of (w,h) for png, gif, or jpg;None
otherwise -
def bunzip(fn)
bunzipfn
, raising exception if output already exists -
def loads(s, **kw)
Same asjson.loads
, but handlesNone
-
def loads_multi(s)
Generator of >=0 decoded json dicts, possibly with non-json ignored text at start and end -
def dumps(obj, **kw)
Same asjson.dumps
, but usesujson
if available -
def untar_dir(fname, dest, rename, overwrite)
untarfile
intodest
, creating a directory if the root contains more than one item -
def repo_details(url)
Tuple ofowner,name
from ssh or https git repourl
-
def run(cmd, *rest)
Passcmd
(splitting withshlex
if string) tosubprocess.run
; returnstdout
; raiseIOError
if fails -
def open_file(fn, mode, **kwargs)
Open a file, with optional compression if gz or bz2 suffix -
def save_pickle(fn, o)
Save a pickle file, to a file name or opened file -
def load_pickle(fn)
Load a pickle file from a file name or opened file -
def parse_env(s, fn)
Parse a shell-style environment string or file -
def expand_wildcards(code)
Expand all wildcard imports in the given code string. -
def dict2obj(d, list_func, dict_func)
Convert (possibly nested) dicts (or lists of dicts) toAttrDict
-
def obj2dict(d)
Convert (possibly nested) AttrDicts (or lists of AttrDicts) todict
-
def repr_dict(d)
Print nested dicts and lists, such as returned bydict2obj
-
def is_listy(x)
isinstance(x, (tuple,list,L,slice,Generator))
-
def mapped(f, it)
mapf
overit
, unless it's not listy, in which case returnf(it)
-
@patch def readlines(self, hint, encoding)
Read the content ofself
-
@patch def read_json(self, encoding, errors)
Same asread_text
followed byloads
-
@patch def mk_write(self, data, encoding, errors, mode)
Make all parent dirs ofself
, and writedata
-
@patch def relpath(self, start)
Same asos.path.relpath
, but returns aPath
, and resolves symlinks -
@patch def ls(self, n_max, file_type, file_exts)
Contents of path as a list -
@patch def delete(self)
Delete a file, symlink, or directory tree -
class IterLen
Base class to add iteration to anything supporting__len__
and__getitem__
def __iter__(self)
-
@docs class ReindexCollection
Reindexes collectioncoll
with indicesidxs
and optional LRU cache of sizecache
def __init__(self, coll, idxs, cache, tfm)
def __getitem__(self, i)
def __len__(self)
def reindex(self, idxs)
def shuffle(self)
def cache_clear(self)
def __getstate__(self)
def __setstate__(self, s)
-
def get_source_link(func)
Return link tofunc
in source code -
def truncstr(s, maxlen, suf, space)
Truncates
to lengthmaxlen
, adding suffixsuf
if truncated -
def sparkline(data, mn, mx, empty_zero)
Sparkline fordata
, withNone
s (and zero, ifempty_zero
) shown as empty column -
def modify_exception(e, msg, replace)
Modifiese
with a custom message attached -
def round_multiple(x, mult, round_down)
Roundx
to nearest multiple ofmult
-
def set_num_threads(nt)
Get numpy (and others) to usent
threads -
def join_path_file(file, path, ext)
Returnpath/file
if file is a string or aPath
, file otherwise -
def autostart(g)
Decorator that automatically starts a generator -
class EventTimer
An event timer with history ofstore
items of timespan
-
def __init__(self, store, span)
-
def add(self, n)
Recordn
events -
@property def duration(self)
-
@property def freq(self)
-
-
def stringfmt_names(s)
Unique brace-delimited names ins
-
class PartialFormatter
Astring.Formatter
that doesn't error on missing fields, and tracks missing fields and unused argsdef __init__(self)
def get_field(self, nm, args, kwargs)
def check_unused_args(self, used, args, kwargs)
-
def partial_format(s, **kwargs)
string formats
, ignoring missing field errors, returning missing and extra fields -
def utc2local(dt)
Convertdt
from UTC to local time -
def local2utc(dt)
Convertdt
from local to UTC time -
def trace(f)
Addset_trace
to an existing functionf
-
@contextmanager def modified_env(*delete, **replace)
Context manager temporarily modifyingos.environ
by deletingdelete
and replacingreplace
-
class ContextManagers
Wrapper forcontextlib.ExitStack
which enters a collection of context managersdef __init__(self, mgrs)
def __enter__(self)
def __exit__(self, *args, **kwargs)
-
def shufflish(x, pct)
Randomly relocate items ofx
up topct
oflen(x)
from their starting location -
def console_help(libname)
Show help for all console scripts fromlibname
-
def hl_md(s, lang, show)
Syntax highlights
usinglang
. -
def type2str(typ)
Stringifytyp
-
class Unset
def __repr__(self)
def __str__(self)
def __bool__(self)
@property def name(self)
-
def nullable_dc(cls)
Likedataclass
, but default ofUNSET
added to fields without defaults -
def flexiclass(cls)
Convertcls
into adataclass
likemake_nullable
. Converts in place and also returns the result. -
def asdict(o)
Converto
to adict
, supporting dataclasses, namedtuples, iterables, and__dict__
attrs. -
def is_typeddict(cls)
Check ifcls
is aTypedDict
-
def is_namedtuple(cls)
True
ifcls
is a namedtuple type -
def flexicache(*funcs)
Likelru_cache
, but customisable with policyfuncs
-
def time_policy(seconds)
Aflexicache
policy that expires cached items afterseconds
have passed -
def mtime_policy(filepath)
Aflexicache
policy that expires cached items afterfilepath
modified-time changes -
def timed_cache(seconds, maxsize)
Likelru_cache
, but also with time-based eviction